Vue3 Custom Directives

In addition to the core directives set by default (v-model and v-show), Vue also allows registering custom directives.

Below we register a global directive v-focus. The function of this directive is to make the element get focus when the page loads:

Example

<div id="app"> <p>When the page loads, the input element automatically gets focus:</p> <input v-focus> </div> <script>``` const app = Vue.createApp({}) // RegisteraglobalCustomDirective `v-focus` app.directive('focus', { // WhenBy绑decideofelement挂loadto DOM Mediumwhen…… mounted(el) { // 聚焦element el.focus() } }) app.mount('#app') ```</script>

Try it »

We can also use the directives option in an instance to register local directives, so that the directive can only be used in this instance:

Example

<div id="app"> <p>When the page loads, the input element automatically gets focus:</p> <input v-focus> </div> <script>``` const app = { data() { return { } }, directives: { focus: { // Directiveofdefinition mounted(el) { el.focus() } } } } Vue.createApp(app).mount('#app') ```

Try it »

Hooks

Hook Functions

The directive definition function provides several hook functions (optional):

  • created : Called before the bound element's attributes or event listeners are applied.

  • beforeMount : Called when the directive is first bound to the element and before the parent component is mounted.

  • mounted : Called after the parent component of the bound element is mounted.

  • beforeUpdate: Called before updating the VNode of the containing component.

  • updated: Called after the VNode of the containing component and the VNodes of its child components are updated.

  • beforeUnmount: Called once before the parent component of the bound element is unmounted.

  • unmounted: Called once when the directive is unbound from the element and the parent component has been unmounted.

Example

import { createApp } from 'vue' const app = createApp({}) //Registration app.directive('my-directive', { //Directives have a set of lifecycle hooks: //Called before the bound element's attributes or event listeners are applied created() {}, //Called before the parent component of the bound element is mounted beforeMount() {}, //Called when the parent component of the bound element is mounted mounted() {}, //Called before the VNode of the containing component is updated beforeUpdate() {}, //Called after the VNode of the containing component and the VNodes of its child components are updated updated() {}, //Called before the parent component of the bound element is unmounted beforeUnmount() {}, //Called when the parent component of the bound element is unmounted unmounted() {} }) //Registration (Functional Directives) app.directive('my-directive', () => { //This will be called as `mounted` and `updated` }) //getter; returns the directive definition if registered const myDirective = app.directive('my-directive')

Hook Function Parameters

The parameters of the hook functions are:

el

elThe element the directive is bound to. This can be used to directly manipulate the DOM.

binding

binding is an object containing the following properties:

  • instance: The component instance using the directive.
  • value: The value passed to the directive. For example, inv-my-directive="1 + 1": The previous value, only in2。
  • oldValue: in, the value isbeforeUpdateandupdated: Available whether or not the value has changed.
  • arg: Parameter passed to the directive (if any). For example inv-my-directive:foo: in, arg is"foo"。
  • modifiers: An object containing modifiers (if any). For example inv-my-directive.foo.bar: in, the modifiers object is{foo: true,bar: true}。
  • dir: An object passed as an argument when registering the directive. For example, in the following directive:
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

dir will be the following object:

{
  mounted(el) {
    el.focus()
  }
}

vnode

Blueprint of the real DOM element received as the el parameter.

prevNode

The previous virtual node, only available in the beforeUpdate and updated hooks.

The following example demonstrates the use of these parameters:

Example

<div id="app"> <div v-example="{ name: 'Example', url: 'www.example.com' }"></div> </div> ​ <script>``` const app = Vue.createApp({}) app.directive('example', (el, binding, vnode) => { console.log(binding.value.name) // => "Example" console.log(binding.value.url) // => "www.example.com" var s = JSON.stringify el.innerHTML = s(binding.value) }) app.mount('#app') ```</script>

Try it »

Sometimes we don't need other hook functions, so we can write a shorthand function as follows:

Vue.directive('example', function (el, binding) {
  // 设置指令的背景颜色
  el.style.backgroundColor = binding.value.color
})

The directive function accepts any legal JavaScript expression. The following example passes in a JavaScript object:

Example

<div id="app"> <div v-example="{ color: 'green', text: 'Example!' }"></div> </div> <script>``` Vue.directive('example', function (el, binding) { // AbbreviationMethodSettingsTextandBackground color el.innerHTML = binding.value.text el.style.backgroundColor = binding.value.color }) new Vue({ el: '#app' }) ```</script>

Try it »
Other Extensions