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

Practical record of MySQL 5.6 master-slave error reporting

1. Problem symptoms Version: MySQL 5.6, using the...

Solutions to common problems using Elasticsearch

1. Using it with redis will cause Netty startup c...

Detailed tutorial on installing mysql 5.7.26 on centOS7.4

MariaDB is installed by default in CentOS, which ...

Vue implements the full selection function

This article example shares the specific code of ...

MySQL date functions and date conversion and formatting functions

MySQL is a free relational database with a huge u...

Windows10 mysql 8.0.12 non-installation version configuration startup method

This article shares the specific steps for config...

Detailed explanation of using Vue custom tree control

This article shares with you how to use the Vue c...

CSS to achieve particle dynamic button effect

Original link https://github.com/XboxYan/no… A bu...

Detailed explanation of 4 common data sources in Spark SQL

Generic load/write methods Manually specify optio...

What are the new features of Apache Spark 2.4, which will be released in 2018?

This article is from the Apache Spark Meetup held...

About MariaDB database in Linux

Table of contents About MariaDB database in Linux...

A brief analysis of how to set the initial value of Linux root

Ubuntu does not allow root login by default, so t...