Vue — Custom Directives
Basic directive
// directives/focus.js
export const vFocus = {
mounted(el) {
el.focus()
}
}
// Usage
<template>
<input v-focus>
</template>
Directive with value
// directives/color.js
export const vColor = {
mounted(el, binding) {
el.style.color = binding.value
},
updated(el, binding) {
el.style.color = binding.value
}
}
// Usage
<p v-color="'red'">Red text</p>
<p v-color="textColor">Dynamic color</p>
Directive hooks
export const vHighlight = {
created(el, binding) {
el.style.background = binding.value || 'yellow'
},
beforeMount(el) {
console.log('Element about to mount')
},
mounted(el) {
console.log('Element mounted')
},
beforeUpdate(el) {
console.log('Element about to update')
},
updated(el) {
console.log('Element updated')
},
beforeUnmount(el) {
console.log('Element about to unmount')
},
unmounted(el) {
console.log('Element unmounted')
}
}
Modifiers
export const vClickOutside = {
mounted(el, binding) {
el._clickOutside = (event) => {
if (!(el === event.target || el.contains(event.target))) {
binding.value(event)
}
}
document.addEventListener('click', el._clickOutside)
},
unmounted(el) {
document.removeEventListener('click', el._clickOutside)
}
}
// Usage
<div v-click-outside="closeDropdown">Menu</div>
Argument
export const vDebounce = {
mounted(el, binding) {
let timeout
el.addEventListener('input', () => {
clearTimeout(timeout)
timeout = setTimeout(() => {
binding.value(el.value)
}, binding.arg || 300)
})
}
}
// Usage
<input v-debounce:500="handleSearch">
Register globally
// main.js
import { vFocus } from './directives/focus'
import { vColor } from './directives/color'
app.directive('focus', vFocus)
app.directive('color', vColor)
Mini Practice
- Create a v-focus directive
- Build a v-click-outside directive
- Add modifiers and arguments
- Register directives globally
Up Next
Continue with Plugins - Adding functionality.
Related Topics
Frequently Asked Questions about Custom Directives
What is Custom Directives in Vue?
Custom Directives is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Custom Directives?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Custom Directives.
Why is Custom Directives important in Vue?
Custom Directives is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.