Vue3 directives property


Vue3 选项式 APIVue3 Options API

In Vue.js,directivesis the property used to register local directives. Throughdirectivesdevelopers can define and use custom directives in the current component, thereby achieving specific DOM operations or behaviors. This article will explain in detaildirectivesthe function, usage, and practical application scenarios of the property.

Directives are a special feature in Vue.js, used to directly manipulate DOM elements. Vue provides many built-in directives (such asv-if、v-for、v-bindetc.), and also allows developers todirectivesdefine custom directives through the property. Custom directives can be locally registered in a component, making them effective only within that component.


Basic usage of the directives property

In Vue3,directivesthe property is an object, where the keys are directive names and the values are objects containing directive hook functions. Commonly used hook functions include:

  • mounted: Called when the bound element is inserted into the DOM.
  • updated: Called when the parent component of the bound element updates.
  • unmounted: Called when the bound element is removed from the DOM.

The following is a simple example showing how to define and use a custom directive:

Example

<template>
  <div v-custom-directive>This is an example of a custom directive</div>
</template>

<script>
export default {
  directives: {
    // Define the custom directive
    customDirective: {
      mounted(el) {
        // When the element is inserted into the DOM, set the background color to yellow
        el.style.backgroundColor = 'yellow';
      },
      updated(el) {
        // When the component updates, set the text color to red
        el.style.color = 'red';
      }
    }
  }
};
</script>

Code Analysis

  1. directivesproperty: Inscriptthroughdirectivesthe property defines a directive namedcustomDirectivedirective
  2. Hook functions:mountedThe hook function is executed when the element is inserted into the DOM, setting the background color to yellow;updatedThe hook function is executed when the component updates, setting the text color to red.
  3. Using the directive: Intemplatethroughv-custom-directiveuse this directive.

Application scenarios of custom directives

Custom directives are very useful in the following scenarios:

  1. DOM manipulation: For example, focusing an input field, modifying element styles, etc.
  2. Third-party library integration: Integrating third-party libraries (such ashighlight.js、Chart.js) with Vue components.
  3. Event listening: Adding specific event listeners to elements to implement complex behaviors.

Vue3 选项式 APIVue3 Options API

Other extensions