Vue custom directive details

Vue custom directive details

1. Background

I was recently interviewing for a job, and the interviewer asked about custom directives. Since I don’t use custom directives very often, I just read the official documentation and roughly knew that I needed to use Vue.directive to customize directives. After the interview, I immediately went online to look for information about custom directives, and found that there is still a lot to learn about custom directives, so I wanted to write a blog to record it and also to spur myself to try more and learn more! ! !

This is the official documentation module about custom instructions; custom instructions include global custom instructions and local custom instructions

2. Local custom instructions

If you want to register local directives, the component also accepts a directives option:

@Component({
  name: "CustomDirectives",
  components: {},
  directives: {
    // Local custom directive custom1: {
      inserted(el) {
        console.log("el", el);
        el.style.position = "absolute";
        el.style.top = "50%";
        el.style.left = "50%";
        el.style.transform = "translate(-50%,-50%)";
        el.innerText = "Loading...";
        el.style.padding = "10px";
        el.style.color = "#333";
      },
    },
  },
})

3. Global custom instructions

Vue.directive("custom2", {
  inserted(el, binding) {
    console.log("binding", binding);
    if (binding && binding.value) {
      el.innerText = "Test global custom instructions";
      console.log("el", el);
      el.style.position = "absolute";
      el.style.top = "50%";
      el.style.left = "50%";
      el.style.transform = "translate(-50%,-50%)";
      el.style.padding = "10px";
      el.style.color = "#333";
    }
  },
});

4.1 Custom command hook function

  • 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 (the parent node is only guaranteed to exist, but not necessarily to have been inserted into the document).
  • update : Called when VNode of the component is updated, but it may happen before its child VNode 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 directive is unbound from the element.

4.2 Hook function parameters

  • el : The element to which the instruction is bound, which can be used to directly manipulate the DOM.
  • binding : an object,

Contains the following properties:

  • name : The name of the directive, 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 of the directive binding, only available in update and componentUpdated hooks. Available whether the value has changed or not.
  • expression : a directive 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 : The virtual node generated by Vue compilation. See VNode API for more details.
  • oldVnode : The previous virtual node, only available in update and componentUpdated hooks.

4.3 Dynamic instruction parameter transmission

Vue.directive("custom2", {
  inserted(el, binding) {
    console.log("binding", binding);
    if (binding && binding.value) {
      el.innerText = "Test global custom instructions";
      console.log("el", el);
      el.style.position = "absolute";
      el.style.top = "50%";
      const arg = (binding as any).arg;
      el.style[arg] = "50%";
      el.style.transform = "translate(-50%,-50%)";
      el.style.padding = "10px";
      el.style.color = "#333";
    }
  },
});


 <div v-custom2:[direction]="true"></div>
 
  private direction = 'left';

5. Extension

After asking about custom instructions, the interviewer asked you what default instructions you usually use?
I answered: v-for v-if v-show v-model and so on. Then the question came---can v-for and v-if be used at the same time? I answered: No, there will be performance issues if used at the same time.
Q: Why are there performance issues?
I answered: If you need to traverse the entire array every time, it will affect the speed, especially when you only need to render a small part.
Q: How to avoid using v-for and v-if together?
I:? ? ? This situation is not often encountered at work. Generally, v-if is put into the traversal loop (in fact, there are still performance issues)
After the interview, I looked up some information and found that v-for and v-if should not be used together, and should be replaced with computed properties when necessary.

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

You may also be interested in:
  • Detailed code about Vue custom instructions to implement element dragging
  • How to write a custom directive for Vue3
  • Explanation and example usage of 4 custom instructions in Vue
  • vue3 custom directive details
  • Detailed explanation of Vue custom instructions
  • Use of vue global custom instructions and local custom instructions

<<:  Superficial Web Design

>>:  Solve the problem of blank gap at the bottom of Img picture

Recommend

Getting Started Tutorial for Beginners: Domain Name Resolution and Binding

So after registering a domain name and purchasing...

Example of building a Jenkins service with Docker

Pull the image root@EricZhou-MateBookProX: docker...

Sample code for converting video using ffmpeg command line

Before starting the main text of this article, yo...

Implementation of MySQL multi-version concurrency control MVCC

Transaction isolation level settings set global t...

Javascript asynchronous programming: Do you really understand Promise?

Table of contents Preface Basic Usage grammar Err...

jQuery canvas draws picture verification code example

This article example shares the specific code of ...

JavaScript manual implementation of instanceof method

1. Usage of instanceof instanceof operator is use...

JavaScript to achieve fancy carousel effect

This article shares two methods of implementing t...

mysql5.7.18.zip Installation-free version configuration tutorial (windows)

This is the installation tutorial of mysql5.7.18....

JS implements simple example code to control video playback speed

introduction I discovered a problem before: somet...

Building the User Experience

<br />Maybe you've just come into a comp...

JavaScript custom calendar effect

This article shares the specific code of JavaScri...

Jmeter connects to the database process diagram

1. Download the MySQL jdbc driver (mysql-connecto...