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() 中添加的事件监听器 } })
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>
If you only need the update function, you can only pass in a function instead of the definition object:
Vue.directive('my-directive', function (value) { // 这个函数会被作为 update() 函数使用})
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('demoDirective', { bind: function () { this.el.style.color = '#fff' this.el.style.backgroundColor = this.arg }, update: function (value) { this.el.innerHTML = 'name - ' + this.name + '<br>' + 'raw - ' + this.raw + '<br>' + 'expression - ' + this.expression + '<br>' + 'argument - ' + this.arg + '<br>' + 'value - ' + value } }); var demo = new Vue({ el: '#demo', data: { msg: 'hello!' } })</script></body></html>
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: 'white', text: 'hello!'"></div>
If you want to use a single directive instance to handle multiple parameters, you can use literal objects as expressions:
<div v-demo="{color: 'white', text: 'hello!'}"></div> Vue.directive('demo', function (value) { console.log(value) // Object {color: 'white', text: 'hello!'}})
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('literal-dir', { isLiteral: true, bind: function () { console.log(this.expression) // 'foo' } })
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('example', { 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('input', this.handler) }, unbind: function () { this.el.removeEventListener('input', this.handler) } })
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('my-directive', { acceptStatement: true, update: function (fn) { // the passed in value is a function which when called, // will execute the "a++" statement in the owner vm's // scope. } })
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('my-directive', { deep: true, update: function (obj) { // 当 obj 内部嵌套的属性变化时也会调用此函数 } })
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('my-directive', { // 和普通指令的 API 一致 bind: function () { // 对 this.el 进行操作... } })When using it, we no longer write it like this:
<div v-my-directive></div>but instead write:
<my-directive></my-directive>
元素指令不能接受参数或表达式,但是它可以读取元素的特性,来决定它的行为。与通常的指令有个很大的不同,元素指令是终结性的,这意味着,一旦 Vue 遇到一个元素指令,它将跳过对该元素和其子元素的编译 - 即只有该元素指令本身可以操作该元素及其子元素。
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
相关阅读:
一个用Vue.js 2.0+做出的石墨文档样式的富文本编辑器
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!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1
Powerful PHP integrated development environment

Notepad++7.3.1
Easy-to-use and free code editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.