What Is a Vue Directive?

Vue directives are special instructions, part of the Vue.js framework, that add behaviour to HTML elements. Combined with Vue's reactivity, they keep the HTML in sync with the application's data model and make interactive applications possible.
Vue directives start with the v- prefix and activate a specific behaviour when added to an HTML element. Some common directives:
- v-bind: binds an HTML attribute to data. For example, you can bind an element's href to a value:
VueCode fragment <a v-bind:href="url">Link</a> - v-model: binds form fields (input, textarea, select) to a data property, so what the user types is stored in the data:
VueCode fragment <input v-model="username" /> - v-for: renders a list by looping over data, for example the items of an array:
VueCode fragment <ul> <li v-for="item in items">{{ item.name }}</li> </ul> - v-if, v-else-if, v-else: render an element only when a condition is true:
VueCode fragment <p v-if="isUserLoggedIn">You are signed in!</p> <p v-else>Please sign in</p> - v-show: like v-if it depends on a condition, but it is lighter: the element always stays in the DOM and is only shown or hidden with CSS:
VueCode fragment <p v-show="isVisible">This text is shown or hidden</p>
These examples show different uses of Vue directives. Directives create a strong link between HTML and JavaScript and give developers flexibility in building interactive, dynamic web applications.
The example below uses all of these directives in one component; run it, type in the input and click the button:
<template>
<a v-bind:href="url">Vue.js documentation</a>
<input v-model="username" placeholder="Your name" />
<p v-if="username">Hello, {{ username }}!</p>
<p v-else>Please type your name.</p>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<p v-show="isVisible">This text is shown and hidden with v-show.</p>
<button @click="isVisible = !isVisible">Show / hide</button>
</template>
<script>
export default {
data() {
return {
url: 'https://vuejs.org',
username: '',
items: [
{ id: 1, name: 'Vue' },
{ id: 2, name: 'React' },
{ id: 3, name: 'Angular' },
],
isVisible: true,
};
},
};
</script>Have a question about this article? Write to me


