10. Explain the role of directives in Vue.js and provide examples of custom directives you've created.

Advanced

10. Explain the role of directives in Vue.js and provide examples of custom directives you've created.

Overview

Directives in Vue.js are special tokens in the markup that tell the library to do something to a DOM element. They play a crucial role in extending the functionality of HTML by providing powerful commands for manipulating the DOM, handling events, and performing data binding. Custom directives allow developers to create reusable directives with custom functionality tailored to specific needs, enhancing the capabilities of their Vue.js applications.

Key Concepts

  • Reactivity and DOM Manipulations: Directives offer a declarative way to reactively apply side effects to the DOM.
  • Custom Directives: Extending Vue with custom directives to handle unique DOM manipulations or integrations.
  • Directive Lifecycle Hooks: Understanding the lifecycle of a directive to properly initialize and clean up directives.

Common Interview Questions

Basic Level

  1. What is a directive in Vue.js?
  2. How do you register a global custom directive in Vue.js?

Intermediate Level

  1. How can custom directives provide more control over DOM manipulation than built-in directives?

Advanced Level

  1. Can you design a custom directive that auto-focuses an element when a page loads and explain its lifecycle hooks?

Detailed Answers

1. What is a directive in Vue.js?

Answer: Directives in Vue.js are special tokens in the markup that instruct the library to perform some DOM manipulation or runtime behavior on the element they are attached to. Built-in directives like v-model, v-if, v-for, and v-bind are commonly used to bind data to the DOM, conditionally render elements, loop through items, and bind attributes respectively.

Key Points:
- Directives are prefixed with v- to indicate they are special attributes provided by Vue.
- They have access to the element they are bound to, enabling direct DOM manipulations.
- Custom directives can be created to perform custom behavior beyond the scope of built-in directives.

Example:

// Using a built-in directive
<input v-model="message" placeholder="Enter a message">

// Creating a simple custom directive globally
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus();
  }
});

2. How do you register a global custom directive in Vue.js?

Answer: To register a global custom directive in Vue.js, you use Vue.directive followed by its name and a definition object. This directive then becomes available for use across your entire Vue.js application.

Key Points:
- Global directives are registered using Vue.directive.
- The definition object can contain several hook functions such as bind, inserted, update, componentUpdated, and unbind.
- It's beneficial for directives that are used across multiple components or throughout the application.

Example:

// Register a global custom directive named 'color'
Vue.directive('color', {
  bind(el, binding, vnode) {
    // Apply the color passed as the directive's value to the element's font color
    el.style.color = binding.value;
  }
});

// Usage in a Vue component
<template>
  <p v-color="'red'">This text will be red.</p>
</template>

3. How can custom directives provide more control over DOM manipulation than built-in directives?

Answer: Custom directives allow developers to directly access and manipulate the DOM to implement complex behavior, animations, or integration with third-party libraries, which might be cumbersome or impossible with built-in directives alone. They offer fine-grained control over the lifecycle of the DOM element they are attached to, including its creation, update, and destruction.

Key Points:
- Direct access to the DOM element for any manipulation.
- Ability to react to changes in bound value or arguments.
- Use of lifecycle hooks for precise control during the directive's lifecycle.

Example:

// Custom directive to integrate a jQuery plugin
Vue.directive('jquery-plugin', {
  inserted: function(el) {
    // Use jQuery with `el` to initialize the plugin
    $(el).pluginName();
  },
  unbind: function(el) {
    // Cleanup plugin instance when the element is removed
    $(el).pluginName('destroy');
  }
});

4. Can you design a custom directive that auto-focuses an element when a page loads and explain its lifecycle hooks?

Answer: A custom directive called v-autofocus can be designed to focus an element as soon as it is inserted into the document. This directive makes use of the inserted lifecycle hook to gain access to the element and apply focus.

Key Points:
- The inserted hook is used because it is called when the bound element has been inserted into its parent node (which ensures it is in the document DOM).
- This directive can be useful in forms, modals, or anywhere immediate user input is encouraged.
- Remember to check if the element can be focused (e.g., it accepts input) to avoid errors.

Example:

// Register a custom directive named 'autofocus'
Vue.directive('autofocus', {
  inserted: function (el) {
    // Focus the element if it is focusable
    if(el.focus) {
      el.focus();
    }
  }
});

// Usage in a Vue component
<template>
  <input v-autofocus>
</template>

This v-autofocus directive demonstrates the use of the inserted lifecycle hook to perform an action right after the element is added to the DOM, ensuring the element is ready to receive focus.