Discover how a tiny attribute can save you hours of repetitive coding!
Why custom directives matter in Vue - The Real Reasons
Imagine you want to add the same special behavior, like focusing an input or formatting text, to many elements on your webpage by writing plain JavaScript for each one.
Manually adding event listeners or DOM changes everywhere is repetitive, easy to forget, and hard to maintain. If you want to change the behavior, you must update every place manually.
Custom directives let you package that behavior once and reuse it easily by adding a simple attribute to any element. Vue handles applying and cleaning up the behavior automatically.
document.querySelectorAll('input').forEach(el => el.focus())<input v-focus /> <!-- with a custom directive 'focus' -->
It enables clean, reusable, and declarative ways to add special behaviors to elements without cluttering your main code.
For example, you can create a custom directive that automatically formats phone numbers as users type, and then use it on every phone input field just by adding one attribute.
Manual DOM handling is repetitive and error-prone.
Custom directives package behavior for easy reuse.
They keep your code clean and maintainable.
Practice
Solution
Step 1: Understand the purpose of custom directives
Custom directives let you add special behaviors to HTML elements that you can reuse.Step 2: Compare with other options
They do not replace components, fetch data, or only style elements; they control DOM behavior.Final Answer:
They add reusable behaviors directly to HTML elements. -> Option AQuick Check:
Custom directives = reusable element behaviors [OK]
- Thinking directives replace components
- Confusing directives with data fetching
- Assuming directives only style elements
focus in Vue 3?Solution
Step 1: Recall Vue 3 global directive registration
In Vue 3, useapp.directive(name, definition)to register directives globally.Step 2: Check the options
app.directive('focus', { mounted(el) { el.focus() } }) usesapp.directivewith a proper object containingmountedhook. Others use wrong methods or syntax.Final Answer:
app.directive('focus', { mounted(el) { el.focus() } }) -> Option CQuick Check:
Vue 3 global directive = app.directive(name, definition) [OK]
- Using Vue.directive instead of app.directive in Vue 3
- Using app.use or app.component incorrectly
- Passing a function instead of an object with hooks
app.directive('highlight', {
mounted(el) {
el.style.backgroundColor = 'yellow'
}
})What will happen when you use
<div v-highlight>Text</div> in your template?Solution
Step 1: Understand the mounted hook effect
Themountedhook runs when the element is inserted, settingbackgroundColorto yellow.Step 2: Analyze the directive usage
Usingv-highlightapplies the directive, so the div's background becomes yellow, not border or text color.Final Answer:
The div's background color will become yellow when inserted into the DOM. -> Option DQuick Check:
mounted hook sets backgroundColor = yellow [OK]
- Confusing background color with border or text color
- Thinking bind hook is required in Vue 3
- Assuming directive does nothing without update hook
app.directive('scroll', {
mounted(el) {
window.addEventListener('scroll', () => {
el.textContent = window.scrollY
})
},
unmounted() {
window.removeEventListener('scroll')
}
})Solution
Step 1: Check event listener removal
removeEventListener requires the same event and handler function to remove the listener properly.Step 2: Analyze the unmounted hook
Here, removeEventListener is called without the handler function, so the listener stays active causing memory leaks.Final Answer:
The removeEventListener call is missing the event handler function. -> Option BQuick Check:
removeEventListener needs event and handler [OK]
- Omitting handler in removeEventListener
- Confusing unmounted with destroyed hook
- Thinking arrow functions cause errors here
v-auto-focus that focuses an input only when it is visible on the page (not hidden by CSS). Which approach best uses custom directives to achieve this?Solution
Step 1: Understand visibility check in directives
Checkingel.offsetParent !== nullconfirms the element is visible (not hidden by CSS).Step 2: Apply focus conditionally in mounted hook
Focusing only when visible avoids errors and unwanted focus on hidden inputs.Step 3: Evaluate other options
Updated hook focusing unconditionally may cause focus flicker; watchers and global listeners add complexity.Final Answer:
In the mounted hook, check if el.offsetParent !== null before calling el.focus(). -> Option AQuick Check:
Check visibility before focus in mounted hook [OK]
- Focusing without visibility check
- Using updated hook causing repeated focus
- Adding unnecessary watchers or global listeners
Ready to prove it?
Pass the test and this pattern moves unknown
