Use the Vue.directive() method to create a custom directive in Vue. The directive name starts with the v- prefix. The directive options include life cycle hooks such as bind, inserted, update, componentUpdated, and unbind, which are used in different situations. Stages manipulate DOM elements. Parameters can be accepted. Add a colon (: parameter name) after the command name to specify the parameters.
Create custom directives in Vue
Pass Vue.directive()## in Vue # Method to create custom directives. This method accepts two parameters: the directive name and an object containing the directive's options.
Command Name
Command name must start with the v- prefix, followed by a camelCase name to identify the directive. For example,v-myDirective.
Directive Options
The Directive Options object can contain the following attributes:Example
For example, create a custom directive calledv-highlight that will add a yellow color to the element Background:
<code class="javascript">Vue.directive('highlight', { bind: function (el, binding, vnode) { el.style.backgroundColor = 'yellow'; } });</code>
<code class="html"><div v-highlight>突出显示此文本</div></code>
Directive with parameters
The directive can also accept parameters. To do this, add a colon (: parameter name) after the directive name. For example, create a custom directive calledv-size that sets the font size of an element to a parameter:
<code class="javascript">Vue.directive('size', { bind: function (el, binding, vnode) { el.style.fontSize = binding.value + 'px'; } });</code>
<code class="html"><div v-size="20">设置字体大小为 20px</div></code>
The above is the detailed content of How to create custom instructions in vue. For more information, please follow other related articles on the PHP Chinese website!