📖 Scenario: You are building a Vue 3 app where you want to highlight text elements when the user hovers over them. Instead of adding the same style repeatedly, you will create a custom directive to handle the highlight effect.
🎯 Goal: Build a Vue 3 component that uses a custom directive called v-highlight to change the background color of text when hovered.
📋 What You'll Learn
Create a Vue 3 component with a list of text items
Define a custom directive named highlight
Make the directive change background color on mouse enter and revert on mouse leave
Apply the v-highlight directive to each text item
💡 Why This Matters
🌍 Real World
Custom directives help you reuse common DOM behavior like animations, focus management, or styling across many components without repeating code.
💼 Career
Understanding custom directives is valuable for Vue developers to create clean, maintainable, and reusable UI behaviors in professional projects.
Progress0 / 4 steps
1
Set up the Vue component with text items
Create a Vue 3 component using the Options API. Inside the component object, define a data() function that returns { items: ["Apple", "Banana", "Cherry"] }. In the template, use <li> elements inside a <ul> to display each item using v-for with item and index as variables.
Vue
Hint
Remember to define data() that returns { items: ["Apple", "Banana", "Cherry"] }. Use v-for with (item, index) in items to loop.
2
Define the custom directive
Before the export default, create a constant called highlight that is an object with two methods: beforeMount and unmounted. In beforeMount, add event listeners to the element parameter el for mouseenter and mouseleave. On mouseenter, set el.style.backgroundColor = 'yellow'. On mouseleave, reset el.style.backgroundColor = ''. Leave unmounted empty for now.
Vue
Hint
Use el.addEventListener inside beforeMount to add mouse events that change el.style.backgroundColor.
3
Register the directive in the component
Add a directives property to the component object (export default). Set directives to an object with a key highlight and value highlight (shorthand).
Vue
Hint
Add directives: { highlight } to the component options.
4
Apply the custom directive in the template
In the <li> element inside the v-for, add the directive v-highlight to apply the highlight effect on hover.
Vue
Hint
Add v-highlight inside the <li> tag to apply the directive.
Practice
(1/5)
1. What is the main purpose of creating a custom directive in Vue?
easy
A. To add reusable behavior to HTML elements
B. To define new components
C. To manage Vuex state
D. To handle routing between pages
Solution
Step 1: Understand what directives do in Vue
Directives are special markers on elements that tell Vue to do something with that element.
Step 2: Identify the role of custom directives
Custom directives let you add reusable behavior to elements, like focusing an input or changing styles dynamically.
Final Answer:
To add reusable behavior to HTML elements -> Option A
Quick Check:
Custom directives = reusable element behavior [OK]
Hint: Custom directives add behavior to elements, not components [OK]
Common Mistakes:
Confusing directives with components
Thinking directives manage app state
Assuming directives handle routing
2. Which of the following is the correct syntax to register a global custom directive named v-focus in Vue 3?
easy
A. Vue.directive('v-focus', function(el) { el.focus() })
B. app.directive('focus', { mounted(el) { el.focus() } })
C. app.directive('v-focus', { bind(el) { el.focus() } })
D. Vue.createDirective('focus', { mounted(el) { el.focus() } })
Solution
Step 1: Recall Vue 3 global directive registration
In Vue 3, you use the app instance's directive method with the directive name without the 'v-' prefix.
Step 2: Check the lifecycle hook and syntax
The correct hook for when the element is inserted is 'mounted', and the function receives the element as argument.
Final Answer:
app.directive('focus', { mounted(el) { el.focus() } }) -> Option B
Quick Check:
Vue 3 global directive = app.directive('name', { mounted }) [OK]
Hint: Use app.directive('name', { mounted }) without 'v-' prefix [OK]
Common Mistakes:
Including 'v-' prefix in directive name
Using Vue.directive instead of app.directive in Vue 3
Using deprecated hooks like 'bind'
3. Given this custom directive registered globally in Vue 3:
What will be the text color of the paragraph after the component updates if used as <p v-color="'red'">Hello</p> and later the binding value changes to 'blue'?
medium
A. The text color will be black (default)
B. The text color will remain red
C. The text color will change to blue
D. There will be a runtime error
Solution
Step 1: Understand directive lifecycle hooks
The 'mounted' hook sets the color initially, and the 'updated' hook runs when the binding value changes.
Step 2: Trace the color change on update
When the binding value changes to 'blue', the 'updated' hook sets the element's color style to 'blue'.
Final Answer:
The text color will change to blue -> Option C
Quick Check:
updated hook changes color to new binding value [OK]
Hint: updated hook runs on binding change to update element [OK]
Common Mistakes:
Assuming color stays as initial value
Ignoring the updated lifecycle hook
Thinking directive causes errors on update
4. Consider this custom directive code snippet in Vue 3:
What is the problem with this directive when the binding value changes?
medium
A. The tooltip title does not update to the new value
B. The directive causes a syntax error
C. The title attribute is removed on update
D. The directive works correctly with no issues
Solution
Step 1: Analyze the updated hook usage
The updated hook sets the title attribute to binding.oldValue, which is the previous value, not the new one.
Step 2: Understand the effect on the tooltip
Because it sets the old value on update, the tooltip does not reflect the new binding value after change.
Final Answer:
The tooltip title does not update to the new value -> Option A
Quick Check:
updated hook must use binding.value, not binding.oldValue [OK]
Hint: Use binding.value in updated hook, not binding.oldValue [OK]
Common Mistakes:
Using binding.oldValue instead of binding.value on update
Assuming no update needed for title
Confusing syntax error with logic error
5. You want to create a custom directive v-auto-focus that automatically focuses an input element only when it is inserted into the DOM and not on updates. Which is the best way to implement this directive in Vue 3?
hard
A. Use the created hook to call el.focus()
B. Use the updated hook to call el.focus() every time the binding changes
C. Use both mounted and updated hooks to call el.focus()
D. Use the mounted hook to call el.focus() and leave updated empty
Solution
Step 1: Identify when to focus the element
The input should be focused only once when inserted, so the 'mounted' hook is the right place.
Step 2: Avoid focusing on updates
Calling focus in 'updated' would focus repeatedly, which is not desired.
Step 3: Understand Vue 3 lifecycle hooks
There is no 'created' hook for directives; 'mounted' is the earliest for DOM access.
Final Answer:
Use the mounted hook to call el.focus() and leave updated empty -> Option D
Quick Check:
Focus on mounted only, not updated [OK]
Hint: Focus in mounted hook only to avoid repeated focusing [OK]
Common Mistakes:
Focusing in updated hook causing repeated focus
Using non-existent created hook for directives
Calling focus multiple times unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.