Bird
Raised Fist0
Vueframework~5 mins

Why custom directives matter in Vue - Quick Recap

Choose your learning style10 modes available
Recall & Review
beginner
What is a custom directive in Vue?
A custom directive in Vue is a special marker in the template that tells Vue to do something specific with the element, like changing its behavior or appearance beyond normal HTML attributes.
Click to reveal answer
beginner
Why do we use custom directives instead of regular components?
Custom directives are used when you want to directly manipulate the DOM or add low-level behavior that components can't easily handle, like focusing an input or adding event listeners.
Click to reveal answer
intermediate
How do custom directives improve code reusability?
They let you package common DOM behaviors into reusable directives, so you can apply the same behavior to many elements without repeating code.
Click to reveal answer
intermediate
What lifecycle hooks are available in Vue custom directives?
Vue custom directives have hooks like created, beforeMount, mounted, beforeUpdate, updated, beforeUnmount, and unmounted to control behavior at different stages of the element's life.
Click to reveal answer
beginner
Give an example of a real-life situation where a custom directive is useful.
For example, automatically focusing an input field when a form appears, so the user can start typing right away without clicking.
Click to reveal answer
What is the main purpose of a custom directive in Vue?
ATo add reusable low-level DOM behavior
BTo create new components
CTo style elements with CSS
DTo manage Vuex state
Which Vue directive lifecycle hook runs when the element is inserted into the DOM?
Aunmounted
Bcreated
Cupdated
Dmounted
When should you prefer a custom directive over a component?
AWhen you want to add behavior to an element without changing its structure
BWhen you want to reuse UI layouts
CWhen you want to manage data
DWhen you want to create routes
Which of these is NOT a benefit of using custom directives?
AAdding low-level element behavior
BImproving accessibility automatically
CChanging component state
DReusing DOM manipulation code
How do custom directives help keep Vue code clean?
ABy styling elements
BBy separating DOM behavior from component logic
CBy handling routing
DBy replacing components
Explain in your own words why custom directives matter in Vue development.
Think about how you might want to add special behavior to elements without changing their structure.
You got /4 concepts.
    Describe a simple example where a custom directive would be better than a component.
    Consider a behavior that affects an element directly, like focusing or highlighting.
    You got /4 concepts.

      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