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

How to use custom directives in Vue.JS

php中世界最好的语言
Release: 2018-03-07 11:50:33
Original
1693 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template