Vue Directives

  • v-if: Conditionally render an element depending on whether a value is truthy or falsy.
  • v-for: Render a list of items based on an array.
  • v-bind: Bind the attribute to an expression thus allowing you updating HTML attributes dynamically.
  • v-on: Listen for DOM events in templates and run methods when the events occur.

Examples:

                                  
<!-- v-if -->
<div v-if="isDisplayed">Displayed when isDisplayed is truthy</div>

<!-- v-for -->
<ul>
   <li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>

<!-- v-bind -->
<img :src="imageUrl" :alt="imageAlt">

<!-- v-on -->
<button @click="handleClick">Click me</button>

                                  
                                

Custom Directives:

Besides built-in directives, Vue.js also lets you define your own custom directives which are useful for encapsulating reusable behavior that can be applied to HTML elements.

Custom directives are registered using the Vue.directive API and it may apply additional element behaviors, bind directly with DOM or change existing directive’s behavior.

Example:

HTML:

                                  
                                  <div v-highlight>Highlighted text</div>
                                  
                                

Javascript:

                                  
// Register a custom directive
Vue.directive('highlight', {
  bind(el, binding) {
    // Manipulate the DOM element
    el.style.backgroundColor = binding.value || 'yellow';
  }
});

                                  
                                

In this example, we have defined a custom directive called highlight, which changes the background color of its target element to yellow.

This directive takes an optional value that specifies the background color; if no value is provided, then the default is yellow. Then we assign a <div> element v-highlight as seen below.

Custom directives play a key role in encapsulating complex functionalities resulting in increased re-usability of Vue.js components.

They allow you to extend the functionality of Vue.js and create custom solutions tailored to your application's specific requirements.