In addition to the default core directives (v-model and v-show), Vue also allows the registration of custom directives. Note that in Vue2.0, the main form and abstraction of code reuse is components - however, in some cases, you still need to perform low-level operations on pure DOM elements, in which case custom directives will be used.
When the page loads, the element will gain focus (note: autofocus does not work on mobile Safari). In fact, as long as you haven't clicked on anything after opening this page, the input box should still be focused. Now let us use instructions to implement this function: (Recommended learning: JavaScript Video Tutorial)
// 注册一个全局自定义指令 `v-focus`Vue.directive('focus', { // 当被绑定的元素插入到 DOM 中时…… inserted: function (el) { // 聚焦元素 el.focus() } })
If you want to register local instructions, the component also accepts a directives option:
directives: { focus: { // 指令的定义 inserted: function (el) { el.focus() } } }
Then you can use the new v-focus attribute on any element in the template, as follows:
<input v-focus>
A directive definition object can provide the following hook functions (all optional):
bind: Called only once, when the directive is bound to an element for the first time. 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 not necessarily inserted into the document).
update: Called when the VNode of the component is updated, but may occur before its child VNode is updated. The value of the directive 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 all the VNode of the component where the instruction is located and its sub-VNodes have been updated.
unbind: Called only once, when the instruction is unbound from the element.
For more JavaScript-related technical articles, please visit the js tutorial column to learn!
The above is the detailed content of vue custom directive. For more information, please follow other related articles on the PHP Chinese website!