Bird
Raised Fist0
Vueframework~10 mins

Why custom directives matter in Vue - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why custom directives matter
Vue Component Renders
↓
Template with Directive
↓
Vue Compiler Detects Directive
↓
Custom Directive Hook Called
↓
Directive Logic Executes
↓
DOM Element Updated
↓
User Sees Effect
Vue renders a component, finds a custom directive in the template, runs its logic, and updates the DOM element accordingly.
Execution Sample
Vue
<template>
  <input v-focus />
</template>
<script>
export default {
  directives: {
    focus: {
      mounted(el) { el.focus() }
    }
  }
}
</script>
This code uses a custom directive 'v-focus' to automatically focus the input element when it appears.
Execution Table
StepActionDirective HookElement StateEffect
1Vue renders componentNo directive hook yetInput element createdNo focus yet
2Vue compiler finds v-focus directivePrepare to call mounted hookInput element readyNo focus yet
3Call mounted(el) hookmounted calledInput element focusedCursor blinks inside input
4User sees input focusedDirective logic doneInput element focusedUser can type immediately
💡 Directive mounted hook ran once, input element is focused, no further action needed
Variable Tracker
VariableStartAfter 1After 2Final
el.focusedfalsefalsefalsetrue
Key Moments - 2 Insights
Why does the input get focused automatically?
Because the custom directive's mounted hook runs after the element is created, calling el.focus() as shown in execution_table step 3.
Can we use custom directives for things other than focus?
Yes, custom directives can run any DOM-related logic when elements mount, update, or unmount, making them very flexible.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step does the input element become focused?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Check the 'Element State' and 'Directive Hook' columns in step 3.
According to variable_tracker, what is the value of el.focused after step 2?
Atrue
Bfalse
Cundefined
Dnull
💡 Hint
Look at the 'After 2' column for el.focused in variable_tracker.
If the mounted hook did not call el.focus(), what would change in the execution table?
AInput element would still be focused at step 3
BDirective hook would not be called at all
CInput element would not be focused after step 3
DUser would see input focused immediately at step 1
💡 Hint
Refer to the 'Effect' column in execution_table step 3 and 4.
Concept Snapshot
Custom directives in Vue let you add special behavior to DOM elements.
They run hooks like mounted when elements appear.
Use them to manipulate elements directly, like focusing inputs.
They keep your templates clean and reusable.
Directive hooks run after element creation, updating the DOM.
This helps add interactive features easily.
Full Transcript
When Vue renders a component, it looks for any custom directives in the template. For example, if an input has a v-focus directive, Vue detects it during compilation. Then Vue calls the directive's mounted hook once the input element is created in the DOM. Inside this hook, the directive runs code like el.focus() to focus the input automatically. This updates the element's state so the user sees the cursor blinking inside the input, ready to type. Custom directives matter because they let you add reusable, direct DOM behavior without cluttering your component logic. They run at specific lifecycle moments, like when elements mount, update, or unmount, giving you control over element behavior. This visual trace shows how the directive hook runs after rendering and changes the element state, making the input focused for the user.

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