0
0
Vueframework~30 mins

Directive with arguments and modifiers in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Vue Directive with Arguments and Modifiers
📖 Scenario: You are building a simple Vue 3 app that changes the background color of a box when you click it. You want to use a custom directive that accepts an argument for the event type and a modifier to control if the event should be captured during the capture phase.
🎯 Goal: Create a Vue 3 component that uses a custom directive with an argument and a modifier to change the background color of a box when clicked. The directive should listen to the event type passed as an argument and respect the capture modifier.
📋 What You'll Learn
Create a Vue 3 component with a <div> box
Define a custom directive called color-change
Use an argument click for the event type in the directive
Use a modifier capture to enable event capturing
Change the box background color to lightblue when the event triggers
💡 Why This Matters
🌍 Real World
Custom directives with arguments and modifiers help you create reusable, flexible behaviors in Vue apps, like handling different events with options.
💼 Career
Understanding Vue directives is important for frontend developers working with Vue to build interactive and maintainable user interfaces.
Progress0 / 4 steps
1
Set up the Vue component with a box
Create a Vue 3 component with a <template> containing a <div> with id="colorBox" and text "Click me".
Vue
Need a hint?

Use a <div> with id="colorBox" inside the <template>.

2
Add a config variable for the color
Inside the <script setup>, create a constant called color and set it to the string 'lightblue'.
Vue
Need a hint?

Use const color = 'lightblue' inside <script setup>.

3
Create the custom directive with argument and modifier
Inside <script setup>, define a custom directive called colorChange that listens to the event type passed as binding.arg and uses the capture modifier from binding.modifiers. When the event triggers, change the element's background color to the color constant.
Vue
Need a hint?

Use binding.arg for the event type and binding.modifiers.capture for the capture option in addEventListener.

4
Use the directive with argument and modifier on the box
In the <template>, add the directive v-color-change:click.capture to the div with id="colorBox". Also, register the directive in the component by adding directives={{ 'color-change': colorChange }} to the <script setup> export.
Vue
Need a hint?

Add v-color-change:click.capture to the div and register the directive using defineExpose with directives.