Detailed explanation of Vue.js directive custom instructions

Detailed explanation of Vue.js directive custom instructions

Customize a demo command

The syntax of Vue custom directives is as follows:

Vue.directive(id, definition)

The two parameters passed in, id refers to the instruction ID, and definition refers to the definition object. Among them, the definition object can provide some hook functions.

<div id="app">
	<!-- Input box gets focus-->
	<input type="text" v-focus/>
</div>

<script>
	// Register a global custom directive v-focus
	Vue.directive("focus", {
		// When the bound element is inserted into the DOM.
		inserted(el, binding) {
			// Focus element el.focus();
		}
	})
</script>
<div id="app">
    <p v-demo:red="msg">{{msg}}</p>
</div>

<script>
	// Global directive Vue.directive('demo', function (el, binding) {
        console.log(el) //p tag console.log(binding) //The output is an object obj
        console.log('Command name:'+binding.name) //Command nameconsole.log('Command binding value:'+binding.value) //Command binding valueconsole.log('String form of binding value:'+binding.expression) //String form of binding valueconsole.log('Parameter passed to the command:'+binding.arg) //Parameter passed to the command})
    var vm = new Vue({
        el: "#app",
        data: {
            msg: 'hello!'
        },
        // Local directives:{
			demo:{
				inserted: function (el) {
					console.log(el)
				}      
			}
		}
    })
</script>

Write the picture description here

Object literals

<div id="app">
    <p v-demo="colours">{{colours.text}}</p>
</div>

<script>
    Vue.directive('demo', function (el, binding) {
        console.log(el) // p tag console.log(binding) // The output is an object obj
        console.log(binding.value) // {color: 'blue',text: 'hello!'}
        console.log(binding.value.color) // 'blue'
        console.log(binding.value.text) // 'hello!'
        el.style = 'color:' + binding.value.color  
    })
    var vm = new Vue({
        el: "#app",
        data: {
            colours:
                color: 'blue',
                text: 'hello!'
            }
        }
    })
</script>

Lifecycle Hooks

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

  1. bind : Called only once, when the directive is first bound to an element. This hook function can be used to define an initialization action that is executed once during binding.
  2. inserted : called when the bound element is inserted into the parent node ( div#app ) (it can be called if the parent node exists, not necessarily in the document).
  3. update : Triggered when the state of the element (VNode-virtual node) bound to the instruction changes (including style, content, Vue data...)
  4. componentUpdated : Called after the VNode of the component where the instruction is located and its child VNodes are all updated.
  5. unbind : Called only once, when the directive is unbound from the element (the element is removed from the DOM).
<div id="app">
    <p v-demo="color">{{num}}</p>
    <button @click="add">Add</button>
    <button onclick='unbind()'>Unbind</button>
</div>

<script>
    function unbind() {
        vm.$destroy(); //Start another method to unbind}
    Vue.directive('demo', { //Five hook functions for registering directives bind: function () { //1. Be bound //Prepare for binding. For example, add event listeners, or other complex operations that only need to be performed once console.log('1 - bind');
        },
        inserted: function () { //2. Bind to the node console.log('2 - inserted');
        },
        update: function () { //3. Component update//Perform corresponding updates based on the new values ​​obtained. For the initial value, console.log('3 - update'); will also be called once.
        },
        componentUpdated: function () { //4. Component update completed console.log('4 - componentUpdated');
        },
        unbind: function () { //5. Unbind//Do cleanup operations. For example, when removing the event listener bound by bind, console.log('5 - bind');
        }
    })
    var vm = new Vue({
        el: "#app",
        data: {
            num: 10,
            color: 'red'
        },
        methods: {
            add: function () {
                this.num++;
            }
        }
    })
</script>

Initialize trigger methods 1 and 2, click the Add button to trigger methods 3 and 4, and click the Unbind button to trigger method 5, as shown below:

Write the picture description here

This is the end of this article about the detailed explanation of Vue.js directive custom instructions. For more relevant Vue.js directive custom instructions, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of custom instructions for Vue.js source code analysis
  • Detailed explanation of learning and using Vue.js custom instructions
  • A brief discussion on how to implement custom drop-down menu instructions in Vue.js
  • Detailed explanation of Vue.js component reusability mixin method and custom directives
  • Detailed implementation of vue.js internal custom instructions and global custom instructions (using directive)
  • Basic usage details of Vue.js custom instructions

<<:  Steps for Docker to build a private warehouse Harbor

>>:  Detailed analysis of mysql MDL metadata lock

Recommend

MySQL derived table (Derived Table) simple usage example analysis

This article uses an example to describe the simp...

HTML reuse techniques

HTML reuse is a term that is rarely mentioned. Tod...

Detailed explanation of soft links and hard links in Linux

Table of contents 1. Basic storage of files and d...

Install mysql5.7.13 using RPM in CentOS 7

0. Environment Operating system for this article:...

Batch replace part of the data of a field in Mysql (recommended)

Batch replace part of the data of a field in MYSQ...

Some suggestions for improving Nginx performance

If your web application runs on only one machine,...

...

jQuery implements the bouncing ball game

This article shares the specific code of jQuery t...

Linux centOS installation JDK and Tomcat tutorial

First download JDK. Here we use jdk-8u181-linux-x...

Detailed steps to install web server using Apache httpd2.4.37 on centos8

Step 1: yum install httpd -y #Install httpd servi...

Basic operation tutorial of files and permissions in centos

Preface Before we begin, we should briefly unders...

Vue realizes the whole process of slider drag verification function

Rendering Define the skeleton, write HTML and CSS...

The visual design path of the website should conform to user habits

Cooper talked about the user's visual path, w...