Vue3 directives Property
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:
mounted: Called when the bound element is inserted into the DOM.updated: Called when the bound element's parent component 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 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
directivesproperty: Inscriptthroughdirectivesproperty defines a directive namedcustomDirective.- Hook Function:
mountedThe hook function executes when the element is inserted into the DOM, setting the background color to yellow;updatedthe hook function executes when the component updates, setting the text color to red. - Using the Directive: In
templatethroughv-custom-directiveuses this directive.
Application Scenarios for Custom Directives
Custom directives are very useful in the following scenarios:
- DOM Manipulation: For example, focusing an input box, modifying element styles, and so on.
- Third-Party Library Integration: Integrating third-party libraries (such as
highlight.js,Chart.js) with Vue components. - Event Listening: Adding specific event listeners to elements to implement complex behaviors.
Vue3 Options API