vue3 custom directive details

vue3 custom directive details

1. Registering custom instructions

The following examples are all custom instructions for implementing an input box to automatically gain focus.

1.1. Global custom instructions

In vue2, global custom directives are mounted on the Vue object through directive , using Vue.directive('name',opt) .

Example 1 : Vue2 global custom instructions

Vue.directive('focus',{

 inserted:(el)=>{

  el.focus()

 }

})

inserted is a hook function that is executed when the bound element is inserted into the parent node.

In vue3 , the vue instance is created through createApp , so the way of mounting global custom directives has also changed, and directive is mounted on the app.

Example 2 : Vue3 global custom instructions

//Global custom directive app.directive('focus',{

 mounted(el){

  el.focus()

 }

})

//Component uses <input type="text" v-focus />



 

1.2. Local custom instructions

In a component, directives are used to introduce local custom directives. The custom directives introduced in Vue2 and Vue3 are exactly the same.

Example 3 : Local custom instructions

<script>

//Local custom instructions const defineDir = {

 focus:

  mounted(el){

   el.focus()

  }

 }

}

export default {

 directives:defineDir,

 setup(){}

}

</script>

2. Lifecycle hook functions in custom instructions

A directive definition object can provide the following hook functions (all optional and introduced as needed)

  • created : Called before a bound element attribute or event listener is applied. This is useful when the directive needs to attach event listeners that need to be called before the normal v-on event listeners.
  • beforeMounted : Executed when the directive is first bound to an element and before the parent component is mounted.
  • mounted : called after the parent component of the bound element is mounted.
  • beforeUpdate : Called before the VNode containing the component is updated.
  • updated : Called after the containing component's VNode and its subcomponents' VNodes are updated.
  • beforeUnmounted : Called before the parent component of the bound element is unmounted
  • unmounted : Called only once, when the directive is unbound from an element and the parent component has been unmounted.

Example 3 : Test the execution of lifecycle functions within instructions

<template>

 <div>

  <input type="text" v-focus v-if="show"><br>

  <button @click="changStatus">{{show?'Hide':'Show'}}</button>

 </div>

</template>

 

//Local custom instructions const autoFocus = {

 focus:

  created(){

   console.log('created');

  },

  beforeMount(){

   console.log('beforeMount');

  },

  mounted(el){

   console.log('mounted');

  },

  beforeUpdated(){

   console.log('beforeUpdated')

  },

  updated(){

   console.log('updated');

  },

  beforeUnmount(){

   console.log('beforeUnmount');

  },

  unmounted(){

   console.log('unmounted');

  }

 },

}

import { ref } from 'vue'

export default {

 directives:autoFocus,

 setup(){

  const show = ref(true)

  return {

   show,

   changStatus(){

    show.value = !show.value

   }

  }

 }

}

 

By clicking the button, we find that when an input element is created, the three hook functions of created , beforeMount and mounted are triggered.

When input element is hidden, beforeUnmount and unmounted will be triggered.

However, beforeUpdate and updated functions we added were not executed.

At this point, if we change v-if on the input element to v-show , the above two methods will be executed. You can verify the specific execution status yourself.

From vue2 to vue3, the lifecycle hook function of custom instructions has changed. The specific changes are as follows:

  • The bind function has been replaced by beforeMounted .
  • update was removed.
  • componentUpdated has been replaced by updated .
  • unbind has been replaced by unmounted .
  • inserted was removed.

3. Parameters of custom instruction hook function

The hook function is given the following parameters:

  • el : The element to which the instruction is bound, which can directly manipulate DOM .
  • binding : is an object containing all the information of the directive.

The properties contained in binding are:

  • arg is the parameter name of the custom instruction.
  • value value bound to the custom directive.
  • The previous value to which oldValue directive was bound.
  • dir hook function executed
  • modifiers : An object containing modifiers.

<template>

 <div>

  <div v-fixed >positioning</div>

 </div>

</template>

 

<script>

//Custom instruction dynamic parameters const autoFocus = {

 fixed:

  beforeMount(el,binding){

   console.log('el',el)

   console.log('binding',binding)

  }

 }

}

export default {

 directives:autoFocus,

 setup(){

 }

}

</script>

4. Custom command parameters

Custom instructions can also have parameters, which can be dynamic and updated in real time based on component instance data.

Example 4 : Customizing dynamic parameters of instructions

<template>

 <div>

  <div v-fixed:pos="posData" style="width:100px;height:100px;background:grey">Positioning</div>

 </div>

</template>

<script>

//Custom instruction dynamic parameters const autoFocus = {

 fixed:

  beforeMount(el,binding){

   el.style.position = "fixed"

   el.style.left = binding.value.left+'px'

   el.style.top = binding.value.top + 'px'

  }

 }

}

export default {

 directives:autoFocus,

 setup(){

  const posData = {

   left:20,

   top:200

  }

  return {

   posData,

  }

 }

}

</script>

When do you need custom directives?

  • It is necessary to perform low-level operations on ordinary DOM elements, and custom instructions will be used at this time.
  • Some functions need to be used on specified DOM elements, but when a large number of DOM elements need to be operated or major changes need to be made, it is recommended to use components instead of directives.

This is the end of this article about the details of vue3 custom instructions. For more relevant vue3 custom instructions, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Understand the usage of Vue2.x and Vue3.x custom instructions and the principle of hook functions
  • Detailed explanation of Vue source code learning callHook hook function
  • Vue3.0 custom instructions (drectives) knowledge summary
  • Use of custom hook function in vue3

<<:  The role and methods of information communication in website visual design (picture and text)

>>:  Summary of pitfalls in virtualbox centos7 nat+host-only networking

Recommend

Detailed explanation of the properties and functions of Vuex

Table of contents What is Vuex? Five properties o...

Docker starts Redis and sets the password

Redis uses the apline (Alps) image of Redis versi...

Vue project @change multiple parameters to pass multiple events

First, there is only one change event. changeleve...

element-ui Mark the coordinate points after uploading the picture

What is element-ui element-ui is a desktop compon...

In-depth understanding of the seven communication methods of Vue components

Table of contents 1. props/$emit Introduction Cod...

Detailed explanation of mysql scheduled tasks (event events)

1. Brief introduction of the event An event is a ...

In-depth study of MySQL composite index

A composite index (also called a joint index) is ...

Research on the value of position attribute in CSS (summary)

The CSS position attribute specifies the element&...

A brief discussion on several situations where MySQL returns Boolean types

mysql returns Boolean type In the first case, ret...

Detailed explanation of three commonly used web effects in JavaScript

Table of contents 1 element offset series 1.1 Off...

Detailed tutorial on installing VirtualBox and Ubuntu 16.04 under Windows system

1. Software Introduction VirtualBox VirtualBox is...