What are custom directives in Vue 3?
Answer
Custom directives allow you to define reusable low-level DOM manipulation logic. Define with lifecycle hooks that receive the DOM element. Global registration: app.directive("focus", { mounted(el) { el.focus(); } });. Usage: <input v-focus>. Directive hooks: app.directive("color", { created(el, binding, vnode) {}, // before attributes are applied beforeMount(el, binding) {}, mounted(el, binding) { el.style.color = binding.value; }, beforeUpdate(el, binding) {}, updated(el, binding) {}, beforeUnmount(el, binding) {}, unmounted(el, binding) {} });. Binding object: binding.value — the directive value: v-color="'red'"; binding.arg — the argument after colon: v-color:background; binding.modifiers — object of modifiers: v-color.once; binding.oldValue — previous value (in updated hook); binding.instance — component instance. Local registration in script setup: const vFocus = { mounted: (el) => el.focus() }; — any variable starting with v is treated as a directive. Shorthand (same for mounted and updated): app.directive("color", (el, binding) => { el.style.color = binding.value; }). Common uses: auto-focus, tooltip, lazy image loading, click-outside detection, intersection observer, copy to clipboard.