0
0
Vueframework~5 mins

Directive with arguments and modifiers in Vue

Choose your learning style9 modes available
Introduction

Directives in Vue help you add special behavior to elements. Arguments and modifiers let you customize how these behaviors work.

When you want to pass extra information to a directive to change its behavior.
When you need to modify how a directive works without writing new code.
When you want to create reusable directives that behave differently based on input.
When you want to handle events with specific keys or conditions using modifiers.
When you want to keep your template clean but still control directive behavior precisely.
Syntax
Vue
<element v-directive:argument.modifier1.modifier2="value"></element>

Argument is a value after a colon (:) that the directive can use.

Modifiers are dot-separated flags that change directive behavior.

Examples
Here, click is the argument for the v-on directive, and prevent is a modifier that stops the default click action.
Vue
<button v-on:click.prevent="submitForm">Submit</button>
The lazy modifier makes v-model update only when the input loses focus, not on every keystroke.
Vue
<input v-model.lazy="username">
A custom directive with argument foo and modifiers bar and baz to customize its behavior.
Vue
<div v-my-directive:foo.bar.baz="someValue"></div>
Sample Program

This Vue component uses the v-on directive with the click argument and prevent modifier. It stops the button's default action (like page reload) and shows a message instead.

Vue
<template>
  <button v-on:click.prevent="showMessage">Click me</button>
  <p>{{ message }}</p>
</template>

<script setup>
import { ref } from 'vue'
const message = ref('')
function showMessage() {
  message.value = 'Button clicked without page reload!'
}
</script>
OutputSuccess
Important Notes

Arguments and modifiers are optional but powerful for customizing directives.

Modifiers are always lowercase and chained with dots.

You can access arguments and modifiers inside custom directive code via binding.arg and binding.modifiers.

Summary

Directives can take arguments to specify what they act on.

Modifiers change how directives behave without extra code.

Use arguments and modifiers to make your Vue templates cleaner and more flexible.