Vue.js provides several built-in directives that offer powerful ways to manipulate the DOM. Directives are special tokens in the markup that tell the library to do something to a DOM element. In this section, we will cover the most commonly used built-in directives in Vue.js.

Key Built-in Directives

  1. v-bind

The v-bind directive is used to bind an attribute to an expression. This is commonly used to dynamically update the class, style, or other attributes of an element.

Example:

<div v-bind:class="dynamicClass"></div>
new Vue({
  el: '#app',
  data: {
    dynamicClass: 'active'
  }
});

In this example, the div element will have the class active.

  1. v-model

The v-model directive creates a two-way binding on an input, textarea, or select element. This is particularly useful for form inputs.

Example:

<input v-model="message" placeholder="Enter a message">
<p>{{ message }}</p>
new Vue({
  el: '#app',
  data: {
    message: ''
  }
});

Here, whatever you type in the input field will be reflected in the p tag.

  1. v-if

The v-if directive is used to conditionally render an element based on the truthiness of an expression.

Example:

<div v-if="isVisible">This is visible</div>
new Vue({
  el: '#app',
  data: {
    isVisible: true
  }
});

If isVisible is true, the div will be rendered.

  1. v-else

The v-else directive must be used immediately after a v-if or v-else-if directive to provide a fallback content.

Example:

<div v-if="isVisible">This is visible</div>
<div v-else>This is not visible</div>
new Vue({
  el: '#app',
  data: {
    isVisible: false
  }
});

If isVisible is false, the second div will be rendered.

  1. v-else-if

The v-else-if directive, as the name suggests, serves as an "else if" block for v-if.

Example:

<div v-if="type === 'A'">Type A</div>
<div v-else-if="type === 'B'">Type B</div>
<div v-else>Other Type</div>
new Vue({
  el: '#app',
  data: {
    type: 'B'
  }
});

If type is 'B', the second div will be rendered.

  1. v-show

The v-show directive toggles the visibility of an element based on the truthiness of an expression. Unlike v-if, v-show does not remove the element from the DOM; it just toggles the display CSS property.

Example:

<div v-show="isVisible">This is visible</div>
new Vue({
  el: '#app',
  data: {
    isVisible: true
  }
});

If isVisible is true, the div will be displayed.

  1. v-for

The v-for directive is used to render a list of items by iterating over an array or an object.

Example:

<ul>
  <li v-for="item in items" :key="item.id">{{ item.text }}</li>
</ul>
new Vue({
  el: '#app',
  data: {
    items: [
      { id: 1, text: 'Item 1' },
      { id: 2, text: 'Item 2' },
      { id: 3, text: 'Item 3' }
    ]
  }
});

This will render a list of items.

  1. v-on

The v-on directive is used to listen to DOM events and execute some JavaScript when they are triggered.

Example:

<button v-on:click="doSomething">Click me</button>
new Vue({
  el: '#app',
  methods: {
    doSomething: function() {
      alert('Button clicked!');
    }
  }
});

When the button is clicked, the doSomething method will be called.

  1. v-pre

The v-pre directive skips compilation for this element and all its children. This can be used to display raw mustache tags.

Example:

<div v-pre>{{ this will not be compiled }}</div>

  1. v-cloak

The v-cloak directive is used to keep the element and its children hidden until Vue's compilation is done. This is useful to prevent the flash of uncompiled mustache tags.

Example:

<style>
[v-cloak] { display: none; }
</style>
<div v-cloak>
  {{ message }}
</div>

  1. v-once

The v-once directive renders the element and component once and skips future updates. This can be used to optimize performance.

Example:

<span v-once>{{ message }}</span>

Practical Exercise

Exercise 1: Using v-if and v-else

Create a simple Vue application that toggles the visibility of a message when a button is clicked.

HTML:

<div id="app">
  <button v-on:click="toggleMessage">Toggle Message</button>
  <p v-if="isVisible">Hello, Vue.js!</p>
  <p v-else>Goodbye, Vue.js!</p>
</div>

JavaScript:

new Vue({
  el: '#app',
  data: {
    isVisible: true
  },
  methods: {
    toggleMessage: function() {
      this.isVisible = !this.isVisible;
    }
  }
});

Solution:

When the button is clicked, the toggleMessage method toggles the isVisible data property, which in turn toggles the visibility of the message.

Exercise 2: Using v-for

Create a Vue application that displays a list of items and allows the user to add new items to the list.

HTML:

<div id="app">
  <ul>
    <li v-for="item in items" :key="item.id">{{ item.text }}</li>
  </ul>
  <input v-model="newItemText" placeholder="Add a new item">
  <button v-on:click="addItem">Add Item</button>
</div>

JavaScript:

new Vue({
  el: '#app',
  data: {
    items: [
      { id: 1, text: 'Item 1' },
      { id: 2, text: 'Item 2' }
    ],
    newItemText: ''
  },
  methods: {
    addItem: function() {
      if (this.newItemText.trim() !== '') {
        this.items.push({ id: this.items.length + 1, text: this.newItemText });
        this.newItemText = '';
      }
    }
  }
});

Solution:

When the "Add Item" button is clicked, the addItem method adds a new item to the items array, and the input field is cleared.

Conclusion

In this section, we covered the most commonly used built-in directives in Vue.js, including v-bind, v-model, v-if, v-else, v-else-if, v-show, v-for, v-on, v-pre, v-cloak, and v-once. These directives provide powerful ways to manipulate the DOM and create dynamic, interactive applications. By practicing with the provided exercises, you should now have a solid understanding of how to use these directives in your Vue.js projects.

© Copyright 2024. All rights reserved