← Back to all snippets
JAVASCRIPT

Creating and Using Custom Directives in Vue 3

Learn to extend Vue 3's capabilities by creating custom directives for low-level DOM manipulation, such as focusing an input on mount or handling external clicks.

// directives/vFocus.js
export const vFocus = {
  mounted: (el) => el.focus()
}

// directives/vClickOutside.js
export const vClickOutside = {
  mounted(el, binding) {
    el.__vueClickOutside__ = event => {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el.__vueClickOutside__)
  },
  unmounted(el) {
    document.removeEventListener('click', el.__vueClickOutside__)
  }
}

// main.js (or App.vue setup)
import { createApp } from 'vue'
import App from './App.vue'
import { vFocus } from './directives/vFocus'
import { vClickOutside } from './directives/vClickOutside'

const app = createApp(App)
app.directive('focus', vFocus)
app.directive('click-outside', vClickOutside)
app.mount('#app')

// MyComponent.vue
<template>
  <input v-focus type="text" placeholder="I will be focused on load">
  <div v-click-outside="handleClickOutside" style="border: 1px solid #ccc; padding: 20px;">
    Click outside this box!
  </div>
  <button>Another element</button>
</template>

<script setup>
const handleClickOutside = () => {
  alert('Clicked outside the box!');
}
</script>
How it works: Custom directives allow direct DOM manipulation beyond standard Vue reactivity. `vFocus` automatically focuses an input when the component mounts. `vClickOutside` detects clicks outside a specific element, useful for dropdowns or modals, demonstrating lifecycle hooks for directives. Registering directives globally in `main.js` makes them available throughout your application.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs