Home Web Front-end JS Tutorial How to use custom directives in Vue.JS

How to use custom directives in Vue.JS

Mar 07, 2018 am 11:50 AM
javascript vue.js customize

This time I will show you how to use the custom instructions of Vue.JS. What are the precautions when using the custom instructions of Vue.JS. The following is a practical case, let’s take a look.

Vue.js allows you to register custom directives, essentially letting you teach Vue some new tricks: how to map data changes to DOM behavior. You can use the Vue.directive(id, definition) method to register a global custom directive by passing in the directive id and definition object. Defining the object requires providing some hook functions (all optional):

bind: Called only once, when the instruction binds the element for the first time.

update: The first time it is called immediately after bind, the parameter obtained is the initial value of the binding; in the future, it will be called whenever the bound value changes, and both the new value and the old value are obtained. parameters.

unbind: Called only once, when the instruction unbinds the element.

Example:

Vue.directive('my-directive', {  bind: function () {    // 做绑定的准备工作
    // 比如添加事件监听器,或是其他只需要执行一次的复杂操作
  },  update: function (newValue, oldValue) {    // 根据获得的新值执行对应的更新
    // 对于初始值也会被调用一次
  },  unbind: function () {    // 做清理工作
    // 比如移除在 bind() 中添加的事件监听器
  }
})
Copy after login

Once the custom directive is registered, you can use it in the Vue.js template like this (you need to add the Vue.js directive prefix, the default is v- ):

<div v-my-directive="someValue"></div>
Copy after login

If you only need the update function, you can only pass in a function instead of the definition object:

Vue.directive(&#39;my-directive&#39;, function (value) {  // 这个函数会被作为 update() 函数使用})
Copy after login

All hook functions will be copied to the actual command object , and this instruction object will be the this
context of all hook functions. Some useful public properties are exposed on the directive object:

el: the element to which the directive is bound
vm: the context ViewModel that owns the directive
expression: the directive's expression , excluding parameters and filters
arg: parameters of the instruction
raw: unparsed raw expression
name: instruction name without prefix

These properties are read-only, do not modify them. You can also attach custom properties to the directive object, but be careful not to overwrite existing internal properties.

Example of using directive object attributes:

<!DOCTYPE html><html><head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/vue/0.12.16/vue.min.js"></script></head><body><div id="demo" v-demo-directive="LightSlateGray : msg"></div><script>
    Vue.directive(&#39;demoDirective&#39;, {
        bind: function () {            this.el.style.color = &#39;#fff&#39;
            this.el.style.backgroundColor = this.arg
        },
        update: function (value) {            this.el.innerHTML =                    &#39;name - &#39;       + this.name + &#39;<br>&#39; +                    &#39;raw - &#39;        + this.raw + &#39;<br>&#39; +                    &#39;expression - &#39; + this.expression + &#39;<br>&#39; +                    &#39;argument - &#39;   + this.arg + &#39;<br>&#39; +                    &#39;value - &#39;      + value
        }
    });    var demo = new Vue({
        el: &#39;#demo&#39;,
        data: {
            msg: &#39;hello!&#39;
        }
    })</script></body></html>
Copy after login

Multiple clauses

Within the same attribute, multiple clauses separated by commas will be bound as multiple directive instances. In the following example, the directive is created and called twice:

<div v-demo="color: &#39;white&#39;, text: &#39;hello!&#39;"></div>
Copy after login

If you want to use a single directive instance to handle multiple parameters, you can use literal objects as expressions:

<div v-demo="{color: &#39;white&#39;, text: &#39;hello!&#39;}"></div>
Vue.directive(&#39;demo&#39;, function (value) {  console.log(value) // Object {color: &#39;white&#39;, text: &#39;hello!&#39;}})
Copy after login

Literal directive

If isLiteral: true is passed when creating a custom directive, the attribute value will be treated as a direct string and assigned to the expression of the directive. Literal instructions do not attempt to establish data monitoring.
Example:

<div v-literal-dir="foo"></div>
Vue.directive(&#39;literal-dir&#39;, {  isLiteral: true,  bind: function () {    console.log(this.expression) // &#39;foo&#39;
  }
})
Copy after login

Dynamic literal directive

However, in the case where the literal directive contains the Mustache tag, the directive behaves as follows:

The directive instance will have an attribute , this._isDynamicLiteral is set to true;

If the update function is not provided, the Mustache expression will only be evaluated once and the value will be assigned to this.expression. No data monitoring is performed on the expression.

If the update function is provided, the instruction will establish a data watch for the expression and call update when the calculation result changes.

Two-way directive

If your directive wants to write data back to the Vue instance, you need to pass in twoWay: true . This option allows using this.set(value) in directives.

Vue.directive(&#39;example&#39;, {  twoWay: true,  bind: function () {    this.handler = function () {      // 把数据写回 vm
      // 如果指令这样绑定 v-example="a.b.c",
      // 这里将会给 `vm.a.b.c` 赋值
      this.set(this.el.value)
    }.bind(this)    this.el.addEventListener(&#39;input&#39;, this.handler)
  },  unbind: function () {    this.el.removeEventListener(&#39;input&#39;, this.handler)
  }
})
Copy after login

Inline Statement

Passing in acceptStatement: true allows the custom directive to accept inline statements like v-on:

<div v-my-directive="a++"></div>
Vue.directive(&#39;my-directive&#39;, {  acceptStatement: true,  update: function (fn) {    // the passed in value is a function which when called,
    // will execute the "a++" statement in the owner vm&#39;s
    // scope.
  }
})
Copy after login

But please use this feature wisely , because generally we want to avoid side effects in templates.

Deep Data Observation

If you want to use a custom instruction on an object, and the update function of the instruction can be triggered when the nested properties inside the object change, then you have to Pass deep: true in the definition of the directive.

<div v-my-directive="obj"></div>
Vue.directive(&#39;my-directive&#39;, {  deep: true,  update: function (obj) {    // 当 obj 内部嵌套的属性变化时也会调用此函数
  }
})
Copy after login

Command priority

You can choose to provide a priority number for the command (default is 0). Instructions with higher priority on the same element will be processed earlier than other instructions. Instructions with the same priority will be processed in the order they appear in the element attribute list, but there is no guarantee that this order is consistent in different browsers.

Generally speaking, as a user, you don’t need to care about the priority of built-in instructions. If you are interested, you can refer to the source code. The logical control instructions v-repeat and v-if are considered "terminal instructions" and they always have the highest priority during the compilation process.

Element Directives

Sometimes, we may want our directives to be available as custom elements rather than as features. This is very similar to the concept of Angular's E-type directives. The element directive can be seen as a lightweight self-defined component (will be discussed later). You can register a custom element directive as follows:

Vue.elementDirective(&#39;my-directive&#39;, {  // 和普通指令的 API 一致
  bind: function () {    // 对 this.el 进行操作...
  }
})
Copy after login

When using it, we no longer write it like this:

<div v-my-directive></div>
Copy after login

but instead write:

<my-directive></my-directive>
Copy after login

元素指令不能接受参数或表达式,但是它可以读取元素的特性,来决定它的行为。与通常的指令有个很大的不同,元素指令是终结性的,这意味着,一旦 Vue 遇到一个元素指令,它将跳过对该元素和其子元素的编译 - 即只有该元素指令本身可以操作该元素及其子元素。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

相关阅读:

怎样在Android开发中与js进行交互

一个用Vue.js 2.0+做出的石墨文档样式的富文本编辑器

用Video.js实现H5直播界面

The above is the detailed content of How to use custom directives in Vue.JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles