0
0
Vueframework~5 mins

Creating custom directives in Vue

Choose your learning style9 modes available
Introduction

Custom directives let you add special behavior to HTML elements easily. They help you reuse code for common tasks.

You want to automatically focus an input box when a page loads.
You need to change an element's style based on some condition.
You want to add or remove event listeners on elements in a reusable way.
You want to create a tooltip that shows when hovering over elements.
You want to detect clicks outside an element to close a dropdown.
Syntax
Vue
app.directive('directive-name', {
  mounted(el, binding) {
    // code to run when element is added to DOM
  },
  updated(el, binding) {
    // code to run when component updates
  },
  unmounted(el) {
    // cleanup code when element is removed
  }
})

The el is the HTML element the directive is attached to.

The binding contains the value passed to the directive.

Examples
This directive automatically focuses an input element when it appears.
Vue
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})
This directive changes the text color of an element based on the passed value.
Vue
app.directive('color', {
  mounted(el, binding) {
    el.style.color = binding.value
  },
  updated(el, binding) {
    el.style.color = binding.value
  }
})
Sample Program

This Vue component uses two custom directives. The v-focus directive sets focus on the input when the page loads. The v-color directive changes the paragraph text color based on the textColor variable. Clicking the button toggles the color between blue and green.

Vue
<template>
  <input v-focus placeholder="Focus on load" />
  <p v-color="textColor">This text changes color.</p>
  <button @click="changeColor">Change Color</button>
</template>

<script setup>
import { ref } from 'vue'

const textColor = ref('blue')

function changeColor() {
  textColor.value = textColor.value === 'blue' ? 'green' : 'blue'
}
</script>

<script>
export default {
  directives: {
    focus: {
      mounted(el) {
        el.focus()
      }
    },
    color: {
      mounted(el, binding) {
        el.style.color = binding.value
      },
      updated(el, binding) {
        el.style.color = binding.value
      }
    }
  }
}
</script>
OutputSuccess
Important Notes

Always clean up event listeners or timers in the unmounted hook to avoid memory leaks.

Use binding.value to get the value passed to the directive.

Directives are great for DOM-related tasks that don't fit well in components.

Summary

Custom directives add reusable behavior to HTML elements.

Use lifecycle hooks like mounted and updated to control behavior.

Directives help keep your templates clean and your code organized.