0
0
Vueframework~5 mins

Why custom directives matter 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 and keep your templates clean.

You want to add a special effect or behavior to many elements, like focusing an input automatically.
You need to manipulate the DOM directly but want to keep your component code simple.
You want to create reusable behaviors that are not covered by built-in Vue features.
You want to separate concerns by moving DOM logic out of your component methods.
You want to improve readability by using clear directive names instead of repeating code.
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 element updates
  }
})
Directives start with 'v-' when used in templates, like
.
The 'el' parameter is the actual HTML element the directive is attached to.
Examples
This directive automatically focuses an input when it appears.
Vue
app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})
Using the custom 'focus' directive on an input element.
Vue
<input v-focus />
Sample Program

This Vue app uses a custom directive 'v-focus' to automatically put the cursor inside the input box when the page loads.

Vue
import { createApp } from 'vue'

const app = createApp({
  template: `<input v-focus placeholder='Focus me automatically' />`
})

app.directive('focus', {
  mounted(el) {
    el.focus()
  }
})

app.mount('#app')
OutputSuccess
Important Notes

Custom directives are great for DOM tasks that Vue's template syntax can't handle directly.

Keep directives focused on one job to make them easy to reuse and maintain.

Summary

Custom directives add reusable behaviors to HTML elements.

They help keep your Vue components clean and simple.

Use them when you need direct DOM control or special effects.