Home >Web Front-end >Vue.js >What is a custom directive in vue? how to use?

What is a custom directive in vue? how to use?

青灯夜游
青灯夜游forward
2022-03-23 11:35:463103browse

This article will take you to understand the custom instructions in vue, and introduce how to register custom instructions, custom instruction parameters, and custom instruction usage scenarios. I hope it will be helpful to everyone!

What is a custom directive in vue? how to use?

Now Vue occupies the majority of the domestic front-end market. During the front-end job search process, there are more and more Vue-related interview questions. A large part of the reason why Vue is so popular is that its progressive, componentized, imperative and other ideas make it very easy for ordinary developers to get started. [Related recommendations: vuejs video tutorial]

Instructions are one of the most used things in a Vue project. Today we will explain a branch of Vue instructions: custom instructions.

1. What is a custom directive?

If we want to use custom instructions, we must first understand what a custom instruction is?

Custom instructions are very easy to understand. The v-for, v-if, v-model, etc. we use are called instructions, and they are also called Vue's built-in instructions. These instructions are all ones we can use directly.

In order to better meet the needs and maximize the personalized development of developers, Vue exposes the API of custom instructions to us, so that in addition to using the built-in instructions, we can also define our own instructions. Once defined, it is very similar to the built-in instructions.

For example, the code we looked at:

<p v-pin="200">我是一段话</p>

Many friends may not know what the v-pin in the above code is. It looks like an instruction, but have you ever encountered it? In fact, v-pin is a custom instruction, but we omit the code to register it here.

2. Environment preparation

For the room, we directly use the scaffolding tool of Vue2.x to quickly build a project.

Build command:

vue create 项目名称

Run it:

What is a custom directive in vue? how to use?

3. How to register Custom instructions?

If we want to use a custom instruction, we must first register it in advance, just like our components, they must be registered before they can be used.

Registration instructions are also divided into global registration and local registration, which are the same as global registration components and local registration components. Globally registered instructions can be used directly in any component, while locally registered instructions can only be used where they are registered.

3.1 Global registration

Global registration As the name suggests, after the custom instruction is registered, it can be used directly in all components of the project.

Vue provides a directive method for us to register custom instructions. We register a global custom instruction in main.js.

The code is as follows:

// src/main.js
import Vue from "vue";
import App from "./App.vue";

Vue.config.productionTip = false;
Vue.directive("resize", {
  bind() {},
  inserted() {},
  update() {},
  componentUpdated() {},
  unbind() {},
});
new Vue({
  render: (h) => h(App),
}).$mount("#app");

In the above code, we directly called the directive method provided by Vue to register the global custom directive. This method receives two parameters: Instruction name, object containing the instruction hook function.

After the command is registered, we can use the command in the form of "v-command name" on elements in any component in the project.

It should be noted that the instruction hook function is not necessary. You can compare it with the life cycle hook function of vue. Their function is to allow instructions to do different things in different processes.

3.2 Local registration

Generally speaking, if the custom instruction is not used by every component, we usually register the custom instruction Just instructions.

Let’s transform the APP.vue file and register custom instructions inside it. The code is as follows:

<script>
export default {
  name: "App",
  components: {},
  directives: {
    resize: {
      bind() {},
      inserted() {},
      update() {},
      componentUpdated() {},
      unbind() {},
    },
  },
};
</script>

As shown above, Vue provides a directives option for us to register custom instructions. At the same level as data and methods, in the above code we registered a custom instruction called resize, which is only allowed to be used inside the component.

Note: Global registration instructions use directives, and local registration instructions use directives. It is easy to understand. Pay attention to registering many local instructions at one time, but only one global instruction can be registered in sequence.

4. Detailed explanation of custom instruction parameters

The previous section briefly introduced the local registration of custom instructions and the global registration of custom instructions. You can see that there are several hook functions in the instructions. , our operation logic mainly lies in these hook functions, so it is necessary for us to introduce these hook functions.

4.1 Introduction to hook function

bind:

Only called once, instruction Called the first time it is bound to an element. One-time initialization settings can be performed here.

inserted:

Called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but it may not have been inserted into the document ).

update:

所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新

componentUpdated:

指令所在组件的 VNode及其子 VNode全部更新后调用。

unbind:

只调用一次,指令与元素解绑时调用。

上面5个就是自定义指令的全部钩子函数,每个钩子函数都是可选的,视情况而定。大家可以简单理解钩子函数顺序:指令绑定到元素时(bind)、元素插入时(inserted)、组件更新时(update)、组件更新后(componentUpdated)、指令与元素解绑时(unbind)。这些和组件的生命周期函数有点类似。

4.2 钩子函数参数介绍

为了方便我们的逻辑操作,每个钩子函数都会接收参数,我们可以用这些参数做我们想做的事。

el:

指令所绑定的元素,可以用来直接操作 DOM。

binding:

一个对象,包含以下属性:

  • name:指令名,不包括 v- 前缀。
  • value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2
  • oldValue:指令绑定的前一个值,仅在 updatecomponentUpdated 钩子中可用。无论值是否改变都可用。
  • expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"
  • arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"
  • modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }

vnode:

Vue 编译生成的虚拟节点。

oldVnode:

上一个虚拟节点,仅在updatecomponentUpdated钩子中可用。

在使用的时候,el和binding参数是我们使用得最平凡的,有了这些参数,我们的操作就变得简单起来。

5. 简单案列实战

上面两节介绍了如何注册自定义指令以及相关参数,接下来就该实战了,我们在APPVue中定义一个自定义指令,先来验证一下钩子函数的执行情况。

代码如下:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <div v-resize></div>
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},
  directives: {
    resize: {
      bind() {
        console.log("bind")
      },
      inserted() {
        console.log("inserted")
      },
      update() {
        console.log("update")
      },
      componentUpdated() {
        console.log("componentUpdated")
      },
      unbind() {
        console.log("unbind")
      },
    },
  },
};
</script>

效果如下:

What is a custom directive in vue? how to use?

上面代码中我们将自定义指令resize绑定到了div元素上面,当我们刷新页面时,执行了自定义指令中的bind和inserted钩子函数,其余函数均要元素有更新才会执行。

5.1 实现v-resize指令

需求背景:

在做数据大屏或者自适应开发的时候,我们通常需要根据浏览器窗口大小的变化重新渲染页面,比如重新绘制echarts图表等功能。

需求描述:

实现自定义指令v-resize指令,窗口大小发生变化时,实时打印最新的窗口宽高。

代码实现:

// src/APP.vue
<template>
  <div id="app">
    <h1>窗口宽度:{{ innerWidth }}</h1>
    <h1>窗口高度:{{ innerHeight }}</h1>
    <div style="height: 300px; width: 80%; background: blue" v-resize></div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      innerHeight: window.innerHeight,
      innerWidth: window.innerWidth,
    };
  },
  components: {},
  directives: {
    resize: {
      bind() {
        console.log("bind");
      },
      inserted(el, binding, vnode) {
        console.log("inserted");
        console.log(el, binding);
        let that = vnode.context;
        // 监听浏览器的resize事件
        window.addEventListener("resize", () => {
          that.innerHeight = window.innerHeight;
          that.innerWidth = window.innerWidth;
        });
      },
      update() {
        console.log("VNode更新了");
      },
      componentUpdated() {
        console.log("componentUpdated");
      },
      unbind() {
        console.log("unbind");
        window.removeEventListener("resize");
      },
    },
  },
};
</script>

效果如下:

What is a custom directive in vue? how to use?

当我们更改浏览器窗口大小时,页面上会实时打印出最新的高度和宽度,当然这儿只是一个最简单的案例,实际项目中我们通常会在窗口大小发生变化后去调用自定义的一些方法。

5.2 指令传参和传值

我们使用v-bind、v-model等内置指令时,都是可以传参和传值的,我们自定义指令也一样。

示例代码:

<template>
  <div id="app">
    <h1>窗口宽度:{{ innerWidth }}</h1>
    <h1>窗口高度:{{ innerHeight }}</h1>
    <div
      style="height: 300px; width: 80%; background: blue"
      v-resize:[args]="value"
    ></div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      innerHeight: window.innerHeight,
      innerWidth: window.innerWidth,
      args: "我是参数",
      value: "我是传的值",
    };
  },
  components: {},
  directives: {
    resize: {
      bind(el, binding) {
        console.log("bind");
        console.log("值", binding.value);
        console.log("参数", binding.arg);
      },
    },
  },
};
</script>

效果如下:

What is a custom directive in vue? how to use?

args和value就是我们传给指令的参数和值,需要注意的是value接收变量或者表达式,arg接收字符串或者变量,具体解释可以参上参数详解那一节。

5.3 指令简写

很多时候我们不需要用到自定义指令中的所有钩子函数,常用的就那么几个,所以官方给我们提供了一种简写的方式。

代码如下:

resize(el, binding) {
   console.log("我是简写的自定义指令", binding.value);
},

上面代码的写法让我们的指令变得很简洁,上段代码的意思就是把bind和update钩子函数合二为一了,通常我们想要这两个钩子函数做同样的事的时候使用。

6. 自定义指令使用场景

知道了自定义指令如何使用,我们可以扩充一下使用场景,加深一下大家对自定义指令的理解。

6.1 v-copy

实现一键复制文本内容,用于鼠标右键粘贴。

6.2 v-longpress

实现长按,用户需要按下并按住按钮几秒钟,触发相应的事件。

6.3 v-debounce

防止按钮在短时间内被多次点击,使用防抖函数限制规定时间内只能点击一次。

6.4 v-LazyLoad

实现一个图片懒加载指令,只加载浏览器可见区域的图片。

6.5 v-draggable

实现一个拖拽指令,可在页面可视区域任意拖拽元素。

上面的一些自定义指令都是需求中非常常见的,对应的指令代码网上也有很多,但是我建议大家自己下去实践一下。

总结

自定义指令的语法规则和用法很简单,复杂的是我们要用来解决什么问题。在合适的场景下使用合适的解决办法才是最重要的。

(学习视频分享:vuejs教程web前端

The above is the detailed content of What is a custom directive in vue? how to use?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete