Vue3 custom instruction


Release date:2024-03-08 Update date:2024-03-16 Editor:admin View counts:143

Label:

Vue3 custom instruction

Except for the core directive of the default setting v-model and v-show Vue also allows you to register custom directives

Let’s register a global directive. The v-focus function of this directive is to get focus on the element when the page is loaded

Example

<divid="app"><p>When loading the page,input
Element automatically obtains focus:</p><inputv-focus></div><script>const app =
Vue.createApp({}) // Register a global custom directive \`v-focus\`
app.directive('focus', { // When the bound element is mounted in the DOM…… mounted(el)
{ // Focusing on elements el.focus() } }) app.mount('#app')</script>

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

Example

<divid="app"><p>When loading the page,input
Element automatically obtains focus:</p><inputv-focus></div><script>const app = { data() {
return { } }, directives: { focus: { // Definition of Instructions mounted(el) {
el.focus() } } } } Vue.createApp(app).mount('#app')

Hook

Hook function

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

  • created :Called before the property or event listener of the bound element is applied.

  • beforeMount :Directive binds to an element for the first time and is called before the parent component is mounted

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

  • beforeUpdate :When updating the VNode called before.

  • updated :In the VNode and its subcomponents VNode called after the update.

  • beforeUnmount :It is called only once when the instruction and before the parent component of the binding element is unloaded.

  • unmounted :Called only once when the instruction is unbound from the element and the parent component has been unloaded

Example

import{createApp}from'vue'constapp=createApp({})//register app.directive('my-directive',{//Instructions are hooks with a set of lifecycles://In the binding element's
attribute
Or before the event listener is appliedcreated(){},//Called before the parent component of the binding element is mounted beforeMount(){},//Called when the parent component of the bound element is mounted mounted(){},//Include components in the
VNode called before updatingbeforeUpdate(){},//In the VNode and its subcomponents that contain components
VNode
Called after update updated(){},//Called before the parent component of the binding element is unloaded beforeUnmount(){},//When unloading the parent component of the bound element, call unmounted () {}})//Register
(Functional instructions)app.directive('my-directive',()=>{//This will be used as \`mounted\` and
\`updated\` call})//getter,
If registered, return instruction definition constmyDirective=app.directive('my-directive')

Hook function parameter

The parameters of the hook function are:

el

The el element to which the instruction is bound. This can be used to manipulate DOM directly.

binding

binding is an object that contains the following properties:

  • instance :An instance of a component that uses instructions

  • value :The value passed to the instruction , for example, in v-my-directive="1 + 1" the value is 2 .

  • oldValue :The previous value, only in the beforeUpdate and updated available in. Whether the value has been changed or not is available.

  • arg :Parameter is passed to the instruction, if any For example, in v-my-directive:foo , arg is "foo" .

  • modifiers :An object that contains modifiers, if any For example, in v-my-directive.foo.bar the modifier object is {foo: true,bar: true} .

  • dir :An object that is passed as a parameter when registering an instruction For example, in the following directive:

app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

dir will be the following objects:

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

vnode

As el the blueprint of the real DOM element received by the parameter.

prevNode

The last virtual node, only in beforeUpdate and updated available in the hook.

The following examples demonstrate the use of these parameters:

Example

<divid="app"><divv-runoob="{ name: 'Rookie Tutorial', url: 'www.runoob.com'
}"></div></div>​<script>const app = Vue.createApp({})
app.directive('runoob', (el, binding, vnode) => {
console.log(binding.value.name) // => "Rookie Tutorial"
console.log(binding.value.url) // => "www.runoob.com" var s =
JSON.stringify el.innerHTML = s(binding.value) })
app.mount('#app')</script>

Sometimes we don’t need other hook functions, we can abbreviate the functions in the following format:

Vue.directive('runoob', function (el, binding) {
  // Set the background color of instructions
  el.style.backgroundColor = binding.value.color
})

The instruction function accepts all valid JavaScript expressions, and the following example passes in a JavaScript object:

Example

<divid="app"><divv-runoob="{ color: 'green', text: 'Rookie Tutorial!'
}"></div></div><script>Vue.directive('runoob', function (el, binding) {
// Set text and background colors in simplified form el.innerHTML = binding.value.text
el.style.backgroundColor = binding.value.color }) new Vue({ el: '#app'
})</script>

Powered by TorCMS (https://github.com/bukun/TorCMS).