YouTip LogoYouTip

Vue3 Directives

Vue Directives are a core feature of Vue.js. They can be used in HTML templates as special attributes starting with v-, and are used to bind reactive data to DOM elements or perform some operations on DOM elements. Vue directives are special HTML attributes with the v- prefix, which give HTML tags additional functionality. Compared to traditional JavaScript methods, creating responsive pages with Vue is much easier and requires less code. Here are some commonly used Vue directives: | Directive | Description | | --- | --- | | `v-bind` | Used to bind data from a Vue instance 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, used to conditionally show or hide elements based on the value of an expression. | | `v-for` | Used to loop through array or object property values to render elements or components. | | `v-on` | Used to attach event listeners to HTML elements, enabling them to trigger methods or functions in the Vue instance. | | `v-model` | Used to create two-way data binding between form controls and Vue instance data. | In addition to these commonly used directives, Vue also provides some other directives such as v-text, v-html, etc., as well as custom directives, allowing developers to manipulate DOM elements more flexibly. ### Examples Here are some examples of using Vue directives: Use v-model directive to implement two-way form data binding: ## Example

{{ message }}

const HelloVueApp = { data() { return { message: 'Hello Vue!!' } } } Vue.createApp(HelloVueApp).mount('#app') [Try it Β»](#) Use v-bind directive to bind data from a Vue instance to the attributes of HTML elements: ## Example
const HelloVueApp = { data() { return { imageSrc: 'https://static.jyshare.com/images/code-icon-script.png' } } } Vue.createApp(HelloVueApp).mount('#app') [Try it Β»](#) Use v-if and v-else directives to conditionally render elements or components based on the value of an expression: ## Example

Hello Vue!

Goodbye Vue!

const HelloVueApp = { data() { return { showMessage: true } } } Vue.createApp(HelloVueApp).mount('#app') [Try it Β»](#) Use v-for directive to loop through array property values to render elements or components: ## Example
  • {{ item.text }}
const HelloVueApp = { data() { return { items: [ { id: 1, text: 'Item 1' }, { id: 2, text: 'Item 2' }, { id: 3, text: 'Item 3' } ] } } } Vue.createApp(HelloVueApp).mount('#app') [Try it Β»](#) Use v-on directive to attach event listeners to HTML elements: ## Example
const app = Vue.createApp({ data() { return { lightOn: false } } }) app.mount('#app') [Try it Β»](#) The following is an example using v-show directive: ## Example

Hello Vue!

const HelloVueApp = { data() { return { showMessage: true } } } Vue.createApp(HelloVueApp).mount('#hello-vue') [Try it Β»](#)
← Python StatisticsMatplotlib Imsave β†’