💚 Vue.js Beginner

What are custom directives in Vue 3?

Why Interviewers Ask This

This is a classic screening question for Vue.js roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

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.

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Vue.js project, I used this when...' immediately makes your answer more credible and memorable.