Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Vue3 directives Property

Vue3 directives Property


Vue3 Options API Vue3 Options API

In Vue.js,directives is the property used to register local directives. Through directives, developers can define and use custom directives within the current component, achieving specific DOM operations or behaviors. This article explains in detail directives the purpose, 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 as v-if, v-for, v-bind , etc.), and also allows developers to define custom directives via directives property. Custom directives can be registered locally within a component, making them effective only inside that component.


Basic Usage of the directives Property

In Vue 3,directives The property is an object where the key is the directive name and the value is an object containing directive hook functions. Commonly used hook functions include:

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 a 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. directives property: In script through directives property defines a directive named customDirective .
  2. Hook Function:mounted The hook function executes when the element is inserted into the DOM, setting the background color to yellow;updated the hook function executes when the component updates, setting the text color to red.
  3. Using the Directive: In template through v-custom-directive uses this directive.

Application Scenarios for Custom Directives

Custom directives are very useful in the following scenarios:

  1. DOM Manipulation: For example, focusing an input box, modifying element styles, and so on.
  2. Third-Party Library Integration: Integrating third-party libraries (such as highlight.js, Chart.js) with Vue components.
  3. Event Listening: Adding specific event listeners to elements to implement complex behaviors.

Vue3 Options API Vue3 Options API