Bird
Raised Fist0
Vueframework~8 mins

Why custom directives matter in Vue - Performance Evidence

Choose your learning style10 modes available
Performance: Why custom directives matter
MEDIUM IMPACT
Custom directives affect how efficiently DOM manipulations happen and how often the browser must recalculate styles and layouts.
Applying repeated DOM updates for element behavior
Vue
const highlightDirective = {
  mounted(el) {
    el.addEventListener('scroll', () => {
      el.style.backgroundColor = 'yellow';
    });
  }
};

const app = Vue.createApp({});
app.directive('highlight', highlightDirective);
Encapsulates DOM logic in a directive, allowing Vue to optimize updates and avoid unnecessary reflows.
📈 Performance GainReduces repeated layout thrashing by isolating DOM changes
Applying repeated DOM updates for element behavior
Vue
const app = Vue.createApp({
  mounted() {
    const el = this.$refs.myElement;
    el.addEventListener('scroll', () => {
      el.style.backgroundColor = 'yellow';
    });
  }
});
Directly manipulating DOM in lifecycle hooks causes repeated style recalculations and layout thrashing on every event.
📉 Performance CostTriggers multiple reflows and repaints on each scroll event
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Direct DOM manipulation in lifecycle hooksHigh (multiple event handlers)Multiple per eventHigh due to frequent style changes[X] Bad
Using custom directives for DOM updatesControlled and isolatedSingle or minimalLower paint cost due to fewer style recalculations[OK] Good
Rendering Pipeline
Custom directives handle DOM updates outside of template re-renders, affecting style calculation and layout stages when they manipulate elements.
→Style Calculation
→Layout
→Paint
⚠️ BottleneckLayout (reflows) caused by frequent or unnecessary DOM changes
Core Web Vital Affected
INP
Custom directives affect how efficiently DOM manipulations happen and how often the browser must recalculate styles and layouts.
Optimization Tips
1Use custom directives to isolate and batch DOM manipulations.
2Avoid direct DOM updates in lifecycle hooks to prevent layout thrashing.
3Monitor layout recalculations in DevTools to catch performance issues.
Performance Quiz - 3 Questions
Test your performance knowledge
Why do custom directives improve performance in Vue?
AThey isolate DOM updates to reduce unnecessary reflows
BThey increase the number of event listeners for better responsiveness
CThey force Vue to re-render the entire component on every change
DThey add extra CSS styles to speed up rendering
DevTools: Performance
How to check: Record a performance profile while interacting with the element using the directive or direct DOM manipulation. Look for layout thrashing and style recalculations.
What to look for: High number of Layout events and long scripting times indicate poor performance; fewer Layout events show better optimization.

Practice

(1/5)
1. Why are custom directives useful in Vue?
easy
A. They add reusable behaviors directly to HTML elements.
B. They replace Vue components entirely.
C. They automatically fetch data from APIs.
D. They style elements with CSS only.

Solution

  1. Step 1: Understand the purpose of custom directives

    Custom directives let you add special behaviors to HTML elements that you can reuse.
  2. Step 2: Compare with other options

    They do not replace components, fetch data, or only style elements; they control DOM behavior.
  3. Final Answer:

    They add reusable behaviors directly to HTML elements. -> Option A
  4. Quick Check:

    Custom directives = reusable element behaviors [OK]
Hint: Custom directives add behaviors to elements, not replace components [OK]
Common Mistakes:
  • Thinking directives replace components
  • Confusing directives with data fetching
  • Assuming directives only style elements
2. Which is the correct syntax to register a global custom directive named focus in Vue 3?
easy
A. app.component('focus', { mounted(el) { el.focus() } })
B. Vue.directive('focus', function(el) { el.focus() })
C. app.directive('focus', { mounted(el) { el.focus() } })
D. app.use('focus', { mounted(el) { el.focus() } })

Solution

  1. Step 1: Recall Vue 3 global directive registration

    In Vue 3, use app.directive(name, definition) to register directives globally.
  2. Step 2: Check the options

    app.directive('focus', { mounted(el) { el.focus() } }) uses app.directive with a proper object containing mounted hook. Others use wrong methods or syntax.
  3. Final Answer:

    app.directive('focus', { mounted(el) { el.focus() } }) -> Option C
  4. Quick Check:

    Vue 3 global directive = app.directive(name, definition) [OK]
Hint: Use app.directive() with hooks to register global directives [OK]
Common Mistakes:
  • Using Vue.directive instead of app.directive in Vue 3
  • Using app.use or app.component incorrectly
  • Passing a function instead of an object with hooks
3. Given this custom directive code:
app.directive('highlight', {
  mounted(el) {
    el.style.backgroundColor = 'yellow'
  }
})

What will happen when you use <div v-highlight>Text</div> in your template?
medium
A. The div will have a yellow border but no background change.
B. The div's text color changes to yellow.
C. Nothing happens because the directive is missing a bind hook.
D. The div's background color will become yellow when inserted into the DOM.

Solution

  1. Step 1: Understand the mounted hook effect

    The mounted hook runs when the element is inserted, setting backgroundColor to yellow.
  2. Step 2: Analyze the directive usage

    Using v-highlight applies the directive, so the div's background becomes yellow, not border or text color.
  3. Final Answer:

    The div's background color will become yellow when inserted into the DOM. -> Option D
  4. Quick Check:

    mounted hook sets backgroundColor = yellow [OK]
Hint: mounted hook runs on insert, sets styles immediately [OK]
Common Mistakes:
  • Confusing background color with border or text color
  • Thinking bind hook is required in Vue 3
  • Assuming directive does nothing without update hook
4. Identify the error in this custom directive code:
app.directive('scroll', {
  mounted(el) {
    window.addEventListener('scroll', () => {
      el.textContent = window.scrollY
    })
  },
  unmounted() {
    window.removeEventListener('scroll')
  }
})
medium
A. The directive should use updated instead of mounted.
B. The removeEventListener call is missing the event handler function.
C. The mounted hook should not use arrow functions.
D. The unmounted hook should be named destroyed.

Solution

  1. Step 1: Check event listener removal

    removeEventListener requires the same event and handler function to remove the listener properly.
  2. Step 2: Analyze the unmounted hook

    Here, removeEventListener is called without the handler function, so the listener stays active causing memory leaks.
  3. Final Answer:

    The removeEventListener call is missing the event handler function. -> Option B
  4. Quick Check:

    removeEventListener needs event and handler [OK]
Hint: Always pass same handler to removeEventListener as added [OK]
Common Mistakes:
  • Omitting handler in removeEventListener
  • Confusing unmounted with destroyed hook
  • Thinking arrow functions cause errors here
5. You want to create a custom directive v-auto-focus that focuses an input only when it is visible on the page (not hidden by CSS). Which approach best uses custom directives to achieve this?
hard
A. In the mounted hook, check if el.offsetParent !== null before calling el.focus().
B. Use the updated hook to call el.focus() unconditionally every time.
C. Add a watcher on a data property to call el.focus() inside the directive.
D. Use a global event listener on window resize to focus the element.

Solution

  1. Step 1: Understand visibility check in directives

    Checking el.offsetParent !== null confirms the element is visible (not hidden by CSS).
  2. Step 2: Apply focus conditionally in mounted hook

    Focusing only when visible avoids errors and unwanted focus on hidden inputs.
  3. Step 3: Evaluate other options

    Updated hook focusing unconditionally may cause focus flicker; watchers and global listeners add complexity.
  4. Final Answer:

    In the mounted hook, check if el.offsetParent !== null before calling el.focus(). -> Option A
  5. Quick Check:

    Check visibility before focus in mounted hook [OK]
Hint: Check element visibility before focus in mounted hook [OK]
Common Mistakes:
  • Focusing without visibility check
  • Using updated hook causing repeated focus
  • Adding unnecessary watchers or global listeners
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard