Back
VueMediumNew
How do you create and use a custom directive in Vue 3?
Object with lifecycle hooks like mounted, updated
Ideal Answer
Custom directives let you apply low-level DOM behavior. They're defined as an object with lifecycle hooks similar to component lifecycle hooks (mounted, updated, unmounted, etc.).
JavaScript
// v-focus: auto-focuses an element when mounted
const vFocus = {
mounted: (el) => el.focus()
}
<script setup>
// available directly since it's a camelCase variable starting with 'v'
</script>
<template>
<input v-focus />
</template>
Globally register with app.directive('focus', { mounted: (el) => el.focus() }). Common use cases: autofocus, click-outside detection, tooltips, permission-based element visibility.