Vue.js Custom Directives
In addition to the core directives set by default (v-model and v-show), Vue also allows registering custom directives.
Below we register a global directive v-focus, which makes the element gain focus when the page loads:
Example
Try it Yourself »
We can also use the directives option in the instance to register local directives, so that the directive can only be used in this instance:
Example
Try it Yourself »
Hooks
Hook Functions
The directive definition function provides several hook functions (optional):
bindCalled only once, when the directive is first bound to the element. This hook function can be used to define an initialization action that executes once when binding.insertedCalled when the bound element is inserted into its parent node (it only needs to exist in the parent node, not necessarily in the document).updateCalled when the template containing the bound element is updated, regardless of whether the binding value changes. By comparing the binding value before and after the update, unnecessary template updates can be ignored (see below for detailed hook function parameters).componentUpdatedCalled when the template containing the bound element completes an update cycle.unbindCalled only once, when the directive is unbound from the element.
Hook Function Parameters
The hook function parameters are:
- elThe element bound to the directive, which can be used to directly manipulate the DOM.
- bindingAn object containing the following properties:
- nameThe directive name, excluding
v-the prefix. - valueThe binding value of the directive, for example:
v-my-directive="1 + 1"the value of value is2。 - oldValueThe previous value bound by the directive, only available in
updateandcomponentUpdatedthe hook. It is available regardless of whether the value changes. - expressionThe expression or variable name of the binding value. For example
v-my-directive="1 + 1"the value of expression is"1 + 1"。 - argThe argument passed to the directive. For example
v-my-directive:foothe value of arg is"foo"。 - modifiersAn object containing modifiers. For example:
v-my-directive.foo.barthe value of the modifiers object is{ foo: true, bar: true }。
- nameThe directive name, excluding
- vnodeThe virtual node generated by Vue compilation.
- oldVnodeThe previous virtual node, only available in
updateandcomponentUpdatedthe hook.
The following example demonstrates the use of these parameters:
Example
Try it Yourself »
Sometimes we do not need other hook functions, and we can use the shorthand form of the function, as follows:
Vue.directive('example', function (el, binding) {
// 设置指令的背景颜色
el.style.backgroundColor = binding.value.color
})
Directive functions can accept all legal JavaScript expressions. The following example passes in a JavaScript object:
Example
Try it Yourself »