0
0
Vueframework~30 mins

Why custom directives matter in Vue - See It in Action

Choose your learning style9 modes available
Why custom directives matter
📖 Scenario: You are building a Vue 3 app that needs to highlight text when the user hovers over it. Instead of repeating the same hover style everywhere, you want to create a reusable custom directive to handle this behavior.
🎯 Goal: Create a Vue 3 app that uses a custom directive called v-highlight to add a yellow background color on hover to any text element.
📋 What You'll Learn
Create a Vue 3 app using the Composition API with <script setup>
Define a custom directive named highlight
The directive should add a yellow background color when the mouse is over the element
The directive should remove the background color when the mouse leaves
Use the directive on a paragraph element in the template
💡 Why This Matters
🌍 Real World
Custom directives let you add reusable behaviors to HTML elements in Vue apps, like tooltips, animations, or input masks.
💼 Career
Understanding custom directives is useful for frontend developers working with Vue to create clean, maintainable, and reusable UI behaviors.
Progress0 / 4 steps
1
Set up the Vue 3 app skeleton
Create a Vue 3 component with <template> and <script setup> tags. Inside the template, add a paragraph with the text Hover over me!.
Vue
Need a hint?

Start by writing the basic Vue 3 component structure with a paragraph inside the template.

2
Create the custom directive variable
Inside the <script setup> tag, create a constant called highlight that is an object with two functions: mounted and unmounted. For now, leave the functions empty.
Vue
Need a hint?

Define the highlight object with mounted and unmounted lifecycle hooks for the directive.

3
Add hover event listeners in the directive
Inside the mounted function of highlight, add event listeners to el for mouseenter and mouseleave. On mouseenter, set el.style.backgroundColor to yellow. On mouseleave, reset el.style.backgroundColor to an empty string. Inside unmounted, remove these event listeners.
Vue
Need a hint?

Use el.addEventListener to add hover handlers and store them on el so you can remove them later.

4
Register and use the custom directive in the template
Register the highlight directive in the component by adding v-highlight to the paragraph element in the template. Also, add directives={{ highlight }} to the <script setup> block using defineExpose or by exporting the directive properly.
Vue
Need a hint?

Add v-highlight to the paragraph and expose the directive using defineExpose with directives: { highlight }.