Complete Guide to Vue.js Directives: Examples and Syntax

Vue.js Directives

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:

  1. 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>
  2. 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>
  3. 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>
  4. 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>
  5. 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>
  6. v-model:
    • Creates two-way data bindings on form input elements or components.
    • Example: <input type="text" v-model="message"><p>{{ message }}</p>
  7. v-pre:
    • Skips compilation for the element and its children, effectively treating them as static content.
    • Example: <pre v-pre>{{ content }}</pre>
  8. v-cloak:
    • Binds to an element to hide it until Vue.js has finished compilation.
    • Example: <div v-cloak>{{ message }}</div>
  9. v-text:
    • Updates the element's text content.
    • Example: <span v-text="text"></span>
  10. v-html:
    • Updates the element's innerHTML.
    • Example: <div v-html="htmlContent"></div>
  11. v-slot:
    • Used with components to define slots for content distribution.
    • Example: <template v-slot:header><h1>Header content goes here</h1></template>
  12. v-on (shorthand: `@`):
    • Attaches event listeners to DOM events.
    • Example: <button @click="handleClick">Click me</button>
  13. 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.

Previous Post Next Post