0
0
Vueframework~8 mins

Creating custom directives in Vue - Performance Optimization Steps

Choose your learning style9 modes available
Performance: Creating custom directives
MEDIUM IMPACT
Custom directives affect how the browser updates and manipulates the DOM, impacting rendering speed and interaction responsiveness.
Applying dynamic styles or behaviors to elements using custom directives
Vue
app.directive('good-style', {
  updated(el, binding) {
    const size = binding.value + 'px';
    const margin = binding.value / 2 + 'px';
    el.style.cssText = `width: ${size}; height: ${size}; margin: ${margin};`;
  }
});
Batching style changes into one update reduces layout recalculations.
📈 Performance GainTriggers a single reflow per update, improving responsiveness.
Applying dynamic styles or behaviors to elements using custom directives
Vue
app.directive('bad-style', {
  updated(el, binding) {
    el.style.width = binding.value + 'px';
    el.style.height = binding.value + 'px';
    el.style.margin = binding.value / 2 + 'px';
  }
});
Multiple style changes trigger separate layout recalculations causing layout thrashing.
📉 Performance CostTriggers 3 reflows per update, slowing interaction responsiveness.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Multiple separate style changes in directiveFew nodes updatedMultiple reflows per updateModerate paint cost[X] Bad
Batch style changes with cssText in directiveFew nodes updatedSingle reflow per updateLower paint cost[OK] Good
Rendering Pipeline
Custom directives modify DOM properties during lifecycle hooks, affecting style calculation and layout stages before painting.
Style Calculation
Layout
Paint
⚠️ BottleneckLayout stage due to multiple style changes causing reflows
Core Web Vital Affected
INP
Custom directives affect how the browser updates and manipulates the DOM, impacting rendering speed and interaction responsiveness.
Optimization Tips
1Batch DOM style changes inside custom directives to avoid multiple reflows.
2Avoid forced synchronous layouts like reading layout properties after style changes.
3Use directive lifecycle hooks efficiently to minimize DOM updates.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance issue when a custom directive updates multiple style properties separately?
AIt improves Largest Contentful Paint (LCP)
BIt triggers multiple layout recalculations causing layout thrashing
CIt reduces the bundle size significantly
DIt prevents any paint operations
DevTools: Performance
How to check: Record a performance profile while interacting with elements using the directive. Look for layout events and style recalculations.
What to look for: Multiple layout thrashing events indicate poor directive performance; fewer layout events show efficient updates.