Vue 3 Custom Directive

Vue 3 Custom Directive

Vue 3 Custom Directive

Custom directives give you direct access to the underlying DOM element when component abstractions are not the right fit.

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

// directives/clickOutside.js
export const vClickOutside = {
  mounted(el, binding) {
    el._clickOutsideHandler = (event) => {
      if (!el.contains(event.target)) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el._clickOutsideHandler)
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutsideHandler)
  }
}
// Register globally in main.js
import { vFocus }        from './directives/focus'
import { vClickOutside } from './directives/clickOutside'

app.directive('focus', vFocus)
app.directive('click-outside', vClickOutside)
<!-- Usage -->
<input v-focus placeholder="Auto-focused on mount" />

<div v-click-outside="closeDropdown">
  <button @click="open = !open">Toggle</button>
  <ul v-show="open">...</ul>
</div>
All Comments