Vue 3 Directives
Vue directives are a core feature of Vue.js. They can be used in HTML templates as special attributes prefixed with v- to bind reactive data to DOM elements or perform operations on DOM elements.
Vue directives are special HTML attributes prefixed with v-, which give HTML tags extra functionality.
Compared with traditional JavaScript methods, using Vue to create reactive pages is much easier and requires less code.
Here are some commonly used Vue directives:
| Instruction | Description |
|---|---|
v-bind |
Used to bind Vue instance data to the attributes of HTML elements. |
v-if |
Used to conditionally render elements or components based on the value of an expression. |
v-show |
v-show is a directive provided by Vue.js to conditionally show or hide an element based on the value of an expression. |
v-for |
Used to loop-render elements or components based on the property values of an array or object. |
v-on |
Used to bind event listeners to HTML elements so they can trigger methods or functions in the Vue instance. |
v-model |
Used to create two-way data binding between form controls and the Vue instance's data. |
In addition to these common directives, Vue provides other directives such as v-text and v-html, as well as custom directives, giving developers more flexibility to manipulate DOM elements.
Example
Here are some examples of using Vue directives:
Use the v-model directive to achieve two-way binding of form data:
Example
{{ message }}
Try it »
Use the v-bind directive to bind Vue instance data to the attributes of HTML elements:
Example
Try it »
Use the v-if and v-else directives to conditionally render elements or components based on the value of an expression:
Example
Hello Vue!
Goodbye Vue!
Try it »
Use the v-for directive to loop-render elements or components based on the property values of an array:
Example
-
{{ item.text }}
Try it »
Use the v-on directive to bind event listeners to HTML elements:
Example
Try it »
Here is an example using the v-show directive:
Example
Hello Vue!
Try it »