0
0
Vueframework~30 mins

Directive hooks (mounted, updated, unmounted) in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Directive Hooks in Vue 3
📖 Scenario: You are building a Vue 3 app where you want to create a custom directive that changes the background color of an element when it is added to the page, updates the color when the bound value changes, and cleans up when the element is removed.
🎯 Goal: Create a custom Vue directive called v-highlight that uses the mounted, updated, and unmounted hooks to manage the background color of an element.
📋 What You'll Learn
Create a Vue 3 app with a custom directive named highlight
Use the mounted hook to set the element's background color to the directive's value
Use the updated hook to update the background color when the value changes
Use the unmounted hook to reset the background color when the element is removed
💡 Why This Matters
🌍 Real World
Custom directives are useful when you want to add reusable behavior to HTML elements in Vue apps, like animations, event handling, or style changes.
💼 Career
Understanding directive hooks helps you build maintainable Vue components and extend Vue's functionality, a valuable skill for frontend developer roles.
Progress0 / 4 steps
1
Create the Vue app and initial directive setup
Create a Vue 3 app using createApp and define a custom directive called highlight with an empty object as its definition.
Vue
Need a hint?

Start by importing createApp from Vue and create an app instance. Then add a directive named highlight with an empty object.

2
Add the mounted hook to set background color
Inside the highlight directive, add the mounted hook that sets the element's background color to the directive's value using el.style.backgroundColor = binding.value.
Vue
Need a hint?

The mounted hook runs when the element is added to the DOM. Use binding.value to get the color value.

3
Add the updated hook to change background color on value change
Add the updated hook inside the highlight directive that updates the element's background color to the new binding.value when the directive's value changes.
Vue
Need a hint?

The updated hook runs when the directive's value changes. Update the background color similarly to mounted.

4
Add the unmounted hook to reset background color
Add the unmounted hook inside the highlight directive that resets the element's background color to an empty string '' when the element is removed from the DOM.
Vue
Need a hint?

The unmounted hook runs when the element is removed. Reset the background color to remove the highlight.