Vue.js Directives


What are directives in Vue.js?

Directives in Vue.js are special tokens in the markup that instruct the Vue instance to do something with the DOM. They are prefixed with v- and provide a way to extend HTML with dynamic behavior, allowing for reactive rendering of the UI based on the application's state.


What are some common built-in directives in Vue.js?

Common built-in directives in Vue.js include:

  • v-bind: Dynamically binds one or more attributes to an expression.
  • v-model: Creates two-way data binding on form input elements.
  • v-if: Conditionally renders an element based on a boolean expression.
  • v-for: Renders a list of elements based on an array or object.
  • v-show: Toggles the visibility of an element based on a boolean expression.
  • v-on: Attaches event listeners to elements.

How do you use the v-bind directive?

The v-bind directive is used to bind an HTML attribute to a Vue instance property or computed property. You can use it to dynamically set attributes like href, src, and class.


const app = new Vue({
  el: '#app',
  data: {
    url: 'https://example.com',
    linkText: 'Visit Example'
  },
  template: `
    <a v-bind:href="url">{{ linkText }}</a>
  `
});

What is the difference between v-if and v-show?

The v-if and v-show directives are both used for conditional rendering, but they operate differently:

  • v-if: Conditionally renders the element and its children in the DOM. If the condition is false, the element is removed from the DOM.
  • v-show: Toggles the visibility of the element by applying CSS styles (e.g., display: none;). The element is always rendered but hidden when the condition is false.

const app = new Vue({
  el: '#app',
  data: {
    isVisible: true
  },
  template: `
    <div>
      <button @click="isVisible = !isVisible">Toggle</button>
      <p v-if="isVisible">This will be rendered if isVisible is true.</p>
      <p v-show="isVisible">This will always be rendered but hidden if isVisible is false.</p>
    </div>
  `
});

How do you use the v-for directive?

The v-for directive is used to render a list of items by iterating over an array or object. You can also use it to access the index of the current item in the loop.


const app = new Vue({
  el: '#app',
  data: {
    items: ['Apple', 'Banana', 'Cherry']
  },
  template: `
    <ul>
      <li v-for="(item, index) in items" :key="index">{{ item }}</li>
    </ul>
  `
});

What is the purpose of the v-on directive?

The v-on directive is used to attach event listeners to DOM elements. It can be used to listen for various events like click, input, and submit, executing specified methods in response.


const app = new Vue({
  el: '#app',
  data: {
    count: 0
  },
  methods: {
    increment() {
      this.count++;
    }
  },
  template: `
    <div>
      <button v-on:click="increment">Count: {{ count }}</button>
    </div>
  `
});

How do you handle events with modifiers in Vue.js?

Modifiers in Vue.js allow you to apply special behavior to events. You can chain them after the event name to modify the default event behavior. Some common modifiers include:

  • stop: Prevents the event from propagating to parent elements.
  • prevent: Prevents the default action of the event (e.g., form submission).
  • once: Ensures the event handler is called only once.

const app = new Vue({
  el: '#app',
  template: `
    <form @submit.prevent="handleSubmit">
      <input type="text" v-model="inputValue" />
      <button type="submit">Submit</button>
    </form>
  `,
  data: {
    inputValue: ''
  },
  methods: {
    handleSubmit() {
      console.log('Form submitted:', this.inputValue);
    }
  }
});

What is a custom directive in Vue.js?

A custom directive in Vue.js is a user-defined directive that allows you to extend the functionality of the built-in directives. You can create custom directives for specific behaviors that are not covered by the standard directives.


// Defining a custom directive
Vue.directive('focus', {
  // When the bound element is inserted into the DOM
  inserted(el) {
    el.focus();
  }
});

const app = new Vue({
  el: '#app',
  template: `<input v-focus placeholder="Focus on me!" />`
});

How do you bind classes and styles dynamically using directives?

You can bind classes and styles dynamically using the v-bind directive for class and style attributes. This allows you to apply classes or inline styles based on component data or computed properties.


const app = new Vue({
  el: '#app',
  data: {
    isActive: true,
    color: 'blue'
  },
  template: `
    <div>
      <p :class="{ active: isActive }">Dynamic class binding</p>
      <p :style="{ color: color }">Dynamic style binding</p>
    </div>
  `
});
Ads