How to declare local directives?
Local directives in Vue are declared directly inside the component, in its directives option (Options API) or through a directive object in <script setup> (Composition API).
They are available only in that component and do not affect others.
Below are the two approaches: Options API and Composition API.
1. Local directives in the Options API
Declared in the component's directives field:
export default {
directives: {
focus: {
mounted(el) {
el.focus()
}
}
}
}Usage:
<input v-focus />Available directive hooks (Vue 3)
A local directive has access to these hooks:
- created - when the directive is first bound
- beforeMount
- mounted
- beforeUpdate
- updated
- beforeUnmount
- unmounted
Example with several hooks:
directives: {
highlight: {
mounted(el) {
el.style.background = 'yellow'
},
updated(el) {
el.style.background = 'lightgreen'
}
}
}2. Local directives in the Composition API (<script setup>)
In <script setup>, directives are declared as an object, exported as v*:
Example
<script setup>
const vFocus = {
mounted(el) {
el.focus()
}
}
</script>
<template>
<input v-focus />
</template>The directive's name equals the variable's name (vFocus -> v-focus).
Example of a more complex directive
<script setup>
const vColor = {
mounted(el, binding) {
el.style.color = binding.value
},
updated(el, binding) {
el.style.color = binding.value
}
}
</script>
<template>
<p v-color="'red'">Text</p>
</template>How to pass arguments and modifiers?
<div v-my-dir:arg.modifier="value"></div>Inside the directive you get:
{
mounted(el, binding) {
console.log(binding.value) // value
console.log(binding.arg) // 'arg'
console.log(binding.modifiers) // { modifier: true }
}
}Summary (great for interviews)
Local directives are declared in the
directivesobject (Options API) or throughvNamevariables in<script setup>. They are available only inside the current component. A directive can contain hooks, mounted, updated, unmounted, etc., and receive a binding (value, arg, modifiers).
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.