Home  >  Article  >  Web Front-end  >  How to create custom instructions in vue

How to create custom instructions in vue

下次还敢
下次还敢Original
2024-04-27 23:33:53374browse

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.

How to create custom instructions in vue

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:

  • bind (optional) on the element Called once when inserting into the DOM.
  • inserted (optional) Called immediately after the element is inserted into the DOM.
  • update (optional) Called when the element is updated.
  • componentUpdated (optional) Called after the parent component is updated.
  • unbind (optional) Called when the element is removed from the DOM.

Example

For example, create a custom directive called

v-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>
Then, you can use this directive in a template:

<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 called

v-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>
You can then use this directive in a template and pass the parameter :

<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!

Statement:
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