Basic usage of custom directives in Vue

Basic usage of custom directives in Vue

Preface

In Vue projects, we often use built-in instructions such as v-show, v-if, v-for, etc. In addition, Vue also provides very convenient custom instructions for us to perform low-level operations on ordinary DOM elements. Make our daily development more convenient and faster. This article summarizes the usage and common scenarios of custom instructions.

text

1. Global Registration

Here we register a directive globally to add a red border to the element using this directive and manipulate the style through the directive.

<div id="app">
    <h1 type="text" v-red>I am an h1 element</h1>
    <div v-red>I am a div element</div>
    <p v-red>I am a p element</p><br>
    <input type="text" v-red><br>
  </div>
  <script>
    Vue.directive("red", {
      // Definition of instruction inserted: function (el) {
        console.log(111);
        el.style.border = "1px solid red"
      }
    })
    new Vue({
      el: "#app",
      data() {
        return {
        }
      },
      methods: {
      }
    })
  </script>

The results are as follows:

In the above code, a global directive is registered through the Vue.directive method. The function receives two parameters. The first parameter is the directive name, which is bound to the element through "v-name" in the element. The second parameter is the hook function that processes the bound element, which will be introduced in detail later.

2. Partial Registration

It is basically the same as the global registration directive, but the scope is different. Here, a custom directive is registered inside the component to set a blue border for the bound elements inside the component.

<div id="app">
    <border-item></border-item>
  </div>
  <script>
    Vue.directive("red", {
      // Definition of instruction inserted: function (el) {
        console.log(111);
        el.style.border = "1px solid red"
      }
    })
    // Define subcomponent Vue.component("border-item", {
      directives: {
        blue:
          // Definition of instruction inserted: function (el) {
            el.style.border = "1px solid blue"
          }
        }
      },
      template: `<div>
                    <h1 v-blue>I am a child component h1 element</h1>
                    <div v-blue>I am a child component div element</div>
                    <p v-blue>I am a child component p element</p><br>
                    Subcomponent<input type="text" v-blue><br>
                    <p v-blue>I am a subcomponent h1 element. I use both global and local custom instructions</p>
                </div>`
    })
    new Vue({
      el: "#app",
      data() {
        return {
        }
      },
      methods: {
      }
    })
  </script>

The results are as follows:

Through the above code, a component that sets a blue border for the bound element is registered in the child component through the directives object. The object passes in a key-value pair, where the key represents the directive name, used through "v-name", and its value corresponds to an object, which contains the relevant hook functions of the directive. The hook function will be explained in detail later.

Note: When the same element uses global and local directives to operate on the same attribute, the local custom directive will be used first. The principle of proximity is adopted here, and the local directive will take precedence over the global directive in calling the unified attribute operation.

3. Hook function and parameter settings

After reading the above introduction, we all know how to use directive, but we still need to understand the hook function inside. Only by understanding the calling time of the hook function can we define a more perfect directive.

A directive definition object can provide the following hook functions (all optional):

* bind: Called only once, when the directive is first bound to an element. Here you can perform a one-time initialization setup.

* inserted: called when the bound element is inserted into the parent node (it only guarantees that the parent node exists, but has not necessarily been inserted into the document).

* update: called when the VNode of the component is updated, but it may happen before its child VNodes are updated. The value of the instruction may or may not have changed. But you can ignore unnecessary template updates by comparing the values ​​before and after the update (see below for detailed hook function parameters).

* componentUpdated: Called after the VNode of the component where the instruction is located and its child VNodes are all updated.

* unbind: Called only once, when the instruction is unbound from the element.

Hook function parameters The following parameters will be passed to the command hook function:

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

* binding: an object containing the following properties:

* name: The command name, without the v- prefix.

* value: the binding value of the directive, for example: in v-my-directive="1+1", the binding value is 2.

* oldValue: The previous value bound to the directive, only available in update and componentUpdated hooks. Available whether the value has changed or not.

* expression: a command expression in string form. For example, in v-my-directive="1+1", the expression is "1+1".

* arg: parameter passed to the command, optional. For example, in v-my-directive:foo, the parameter is "foo".

* modifiers: An object containing modifiers. For example: in v-my-directive.foo.bar, the modifier object is {foo:true,bar:true}.

* vnode: virtual node generated by Vue compilation.

* oldVnode: The previous virtual node, only available in update and componentUpdated hooks.

4. Flexible usage

(1) Dynamic instruction parameters

The parameters of a directive can be dynamic. For example, in v-mydirective:[argument]="value", the argument parameter can be updated according to the component instance data! This allows custom directives to be used flexibly in applications. In the following example, directives are set to implement element border binding and element background property binding.

<div id="app">
    <h1 v-border="redBorder">I am the element 1 of the dynamic instruction parameter</h1> 
     <h1 v-color:[pro]="redBg">I am the element 2 of the dynamic instruction parameter</h1>
  </div>
  <script>
    Vue.directive("border", {
      bind: function (el, binding, vnode) {
        console.log("el", el);
        console.log("binding", binding);
        console.log("vnode", vnode);
        el.style.border = binding.value
      }
    })
    Vue.directive("color", {
      bind: function (el, binding, vnode) {
        console.log("el", el);
        console.log("binding", binding);
        console.log("vnode", vnode);
        el.style[binding.arg] = binding.value
      }
    })
    new Vue({
      el: "#app",
      data() {
        return {
          redBorder: "1px solid red",
          pro: "backgroundColor",
          redBg: "green"
        }
      },
      methods: {
      }
    })
  </script>

The results are as follows:

By the way, take a look at the printed parameters:

The above code introduces two methods of dynamic parameter custom instructions. It is very flexible to use and you can choose the appropriate method according to actual needs.

(2) Function abbreviation

In many cases, you may want to trigger the same behavior on bind and update, and don't care about other hooks. For example, write:

    Vue.directive("border", 
      function (el, binding, vnode) {
        el.style.border = binding.value
      }
    )

(3) Object literal method

When binding the element of the custom directive, pass in data in the format of an object, and then use it in the function shorthand way.

<div id="app">
    <h1 v-color="{ color: 'red', text: 'hello!' }">I am an object literal</h1>
  </div>
  <script>
    // Object literal Vue.directive('color', function (el, binding) {
      console.log(binding.value.color) // => "red"
      console.log(binding.value.text) // => "hello!"
      el.style.color = binding.value.color
      el.innerHTML = binding.value.text
    })
    new Vue({
      el: "#app",
      data() {
        return {
        }
      },
      methods: {
      }
    })
  </script>

The results are as follows:

5. Usage scenarios

In addition to the above usage scenarios, for example, we use custom instructions in the project to control the permission issues of a front-end page. A parameter is set in the instruction. When the page is loaded or the submission event is triggered, the event of the custom instruction is executed first to request and verify whether there is this permission and perform corresponding operations. There are many places where it can be used, and it needs to be practiced continuously in the project. There may be other alternative methods that are not used, which requires us to continue to learn and consolidate these basic knowledge and apply the best solution to complete the project.

Final Thoughts

This concludes this article on the basic usage of custom directives in Vue. For more information on the usage of custom directives in Vue, please search 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:
  • Vue custom directive details
  • A detailed guide to custom directives in Vue
  • Understand the usage of Vue2.x and Vue3.x custom instructions and the principle of hook functions
  • Detailed explanation of Vue.js directive custom instructions
  • Practice of Vue global custom instruction Modal drag
  • Vue custom instructions to achieve pop-up window drag four-side stretching and diagonal stretching effect
  • Detailed explanation of Vue custom instructions

<<:  MySQL8 Installer version graphic tutorial

>>:  Summary of methods for writing judgment statements in MySQL

Recommend

How to configure anti-hotlinking for nginx website service (recommended)

1. Principle of Hotlinking 1.1 Web page preparati...

Vue implements the frame rate playback of the carousel

This article example shares the specific code of ...

Detailed explanation of Django+Vue+Docker to build an interface testing platform

1. Two words at the beginning Hello everyone, my ...

Advanced Usage Examples of mv Command in Linux

Preface The mv command is the abbreviation of mov...

MySQL DATE_ADD and ADDDATE functions add a specified time interval to a date

MySQL DATE_ADD(date,INTERVAL expr type) and ADDDA...

A brief discussion on creating cluster in nodejs

Table of contents cluster Cluster Details Events ...

Embedded transplant docker error problem (summary)

After a long period of transplantation and inform...

Pure CSS implementation of radio and checkbox effect example

radio-and-checkbox Pure CSS to achieve radio and ...

How to remove the blue box that appears when the image is used as a hyperlink

I recently used Dreamweaver to make a product pres...

VMware virtual machine installation Apple Mac OS super detailed tutorial

Table of contents Summarize Sometimes we need to ...

Getting started with JavaScript basics

Table of contents 1. Where to write JavaScript 2....

Write a formal blog using XHTML CSS

The full name of Blog should be Web log, which mea...

How to find and delete duplicate records in MySQL

Hello everyone, I am Tony, a teacher who only tal...

The difference between HTML name id and class_PowerNode Java Academy

name Specify a name for the tag. Format <input...