Beginner LevelVue JS
How do you create custom directives like v-focus or v-click-outside in Vue 3?
❓ Interview Prompt: Explain custom directives, DOM lifecycle hooks (mounted, updated, unmounted), and directive binding values.
Custom directives allow attaching custom low-level DOM behavior to elements.
Naming & Lifecycle:
In '<script setup>', any camelCase variable starting with a lowercase 'v' (like 'vFocus') is automatically registered as a custom directive!
•
Directive objects define lifecycle hooks: 'created', 'beforeMount', 'mounted', 'updated', 'unmounted'.
Code Implementation Example
html
<script setup>
// Custom directive variable starting with 'v'
const vFocus = {
mounted: (el) => el.focus()
};
const vTooltip = {
mounted: (el, binding) => {
el.setAttribute('title', binding.value);
}
};
</script>
<template>
<input v-focus type="text" />
<button v-tooltip="'Click to save changes'">Save</button>
</template>💡Creating and applying custom directives (v-focus and v-tooltip) in script setup.
🎯 Interview Key Takeaway
Custom directives (vFocus) attach DOM lifecycle hooks directly to underlying HTML elements.
#Custom Directives#v-focus#Directives#Beginner
Back to all Vue JS Questions→