Custom directives let you add special behavior to HTML elements easily. They help you reuse code for common tasks.
Creating custom directives in Vue
app.directive('directive-name', { mounted(el, binding) { // code to run when element is added to DOM }, updated(el, binding) { // code to run when component updates }, unmounted(el) { // cleanup code when element is removed } })
The el is the HTML element the directive is attached to.
The binding contains the value passed to the directive.
app.directive('focus', {
mounted(el) {
el.focus()
}
})app.directive('color', {
mounted(el, binding) {
el.style.color = binding.value
},
updated(el, binding) {
el.style.color = binding.value
}
})This Vue component uses two custom directives. The v-focus directive sets focus on the input when the page loads. The v-color directive changes the paragraph text color based on the textColor variable. Clicking the button toggles the color between blue and green.
<template> <input v-focus placeholder="Focus on load" /> <p v-color="textColor">This text changes color.</p> <button @click="changeColor">Change Color</button> </template> <script setup> import { ref } from 'vue' const textColor = ref('blue') function changeColor() { textColor.value = textColor.value === 'blue' ? 'green' : 'blue' } </script> <script> export default { directives: { focus: { mounted(el) { el.focus() } }, color: { mounted(el, binding) { el.style.color = binding.value }, updated(el, binding) { el.style.color = binding.value } } } } </script>
Always clean up event listeners or timers in the unmounted hook to avoid memory leaks.
Use binding.value to get the value passed to the directive.
Directives are great for DOM-related tasks that don't fit well in components.
Custom directives add reusable behavior to HTML elements.
Use lifecycle hooks like mounted and updated to control behavior.
Directives help keep your templates clean and your code organized.