跳到主要内容

Custom Directives

A custom directive is defined as an object containing lifecycle hooks similar to those of a component. The hooks receive the element the directive is bound to

In <script setup>, any camelCase variable that starts with the v prefix can be used as a custom directive

<script setup>
// enables v-focus in templates
const vFocus = {
mounted: (el) => el.focus()
}
</script>

<template>
<input v-focus />
</template>
const app = createApp({})

// make v-focus usable in all components
app.directive('focus', {
/* ... */
})

Directive Hooks

const myDirective = {
// called before bound element's attributes
// or event listeners are applied
created(el, binding, vnode) {
// see below for details on arguments
},
// called right before the element is inserted into the DOM.
beforeMount(el, binding, vnode) {},
// called when the bound element's parent component
// and all its children are mounted.
mounted(el, binding, vnode) {},
// called before the parent component is updated
beforeUpdate(el, binding, vnode, prevVnode) {},
// called after the parent component and
// all of its children have updated
updated(el, binding, vnode, prevVnode) {},
// called before the parent component is unmounted
beforeUnmount(el, binding, vnode) {},
// called when the parent component is unmounted
unmounted(el, binding, vnode) {}
}