0
0
Vueframework~30 mins

Creating custom directives in Vue - Try It Yourself

Choose your learning style9 modes available
Creating Custom Directives in Vue
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Add v-highlight inside the <li> tag to apply the directive.