Complete Guide to Vue.js Directives: Examples and Syntax
In Vue.js, directives are special tokens in the markup that tell the library to do something to a DOM element or component. They are prefixed with v- and are Vue-specific attributes added to HTML elements. Directives are used to apply reactive behavior to the DOM.
There are several built-in directives available in Vue.js:
- v-if:
- Conditionally renders a block of HTML based on the provided expression's truthiness.
- Example:
<div v-if="isTrue">This will only render if isTrue is true.</div>
- v-show:
- Conditionally shows or hides an element based on the provided expression's truthiness.
- Example:
<div v-show="isVisible">This will be shown or hidden based on the value of isVisible.</div>
- v-for:
- Renders a block of HTML or a component multiple times based on an array or an object's properties.
- Example:
<ul><li v-for="item in items" :key="item.id">{{ item.name }}</li></ul>
- v-once:
- Renders an element and its children only once, and subsequently treats them as static content.
- Example:
<span v-once>This will only be compiled once and will not be updated afterwards.</span>
- v-bind (shorthand: `:`):
- Binds an HTML attribute to an expression or a component prop.
- Example:
<div :class="className">This div's class will be bound to the value of className.</div>
- v-model:
- Creates two-way data bindings on form input elements or components.
- Example:
<input type="text" v-model="message"><p>{{ message }}</p>
- v-pre:
- Skips compilation for the element and its children, effectively treating them as static content.
- Example:
<pre v-pre>{{ content }}</pre>
- v-cloak:
- Binds to an element to hide it until Vue.js has finished compilation.
- Example:
<div v-cloak>{{ message }}</div>
- v-text:
- Updates the element's text content.
- Example:
<span v-text="text"></span>
- v-html:
- Updates the element's innerHTML.
- Example:
<div v-html="htmlContent"></div>
- v-slot:
- Used with components to define slots for content distribution.
- Example:
<template v-slot:header><h1>Header content goes here</h1></template>
- v-on (shorthand: `@`):
- Attaches event listeners to DOM events.
- Example:
<button @click="handleClick">Click me</button>
- v-spread:
- Spreads attributes onto a component.
- Example:
<MyComponent v-spread="props"></MyComponent>
In features blogs we'll discuss about the each directives with detailed examples.