Custom directives let you add special behavior to HTML elements easily. They help you reuse code for common tasks.
Creating custom directives in Vue
app.directive('directive-name', { mounted(el, binding) { // code to run when element is added to DOM }, updated(el, binding) { // code to run when component updates }, unmounted(el) { // cleanup code when element is removed } })
The el is the HTML element the directive is attached to.
The binding contains the value passed to the directive.
app.directive('focus', {
mounted(el) {
el.focus()
}
})app.directive('color', {
mounted(el, binding) {
el.style.color = binding.value
},
updated(el, binding) {
el.style.color = binding.value
}
})This Vue component uses two custom directives. The v-focus directive sets focus on the input when the page loads. The v-color directive changes the paragraph text color based on the textColor variable. Clicking the button toggles the color between blue and green.
<template> <input v-focus placeholder="Focus on load" /> <p v-color="textColor">This text changes color.</p> <button @click="changeColor">Change Color</button> </template> <script setup> import { ref } from 'vue' const textColor = ref('blue') function changeColor() { textColor.value = textColor.value === 'blue' ? 'green' : 'blue' } </script> <script> export default { directives: { focus: { mounted(el) { el.focus() } }, color: { mounted(el, binding) { el.style.color = binding.value }, updated(el, binding) { el.style.color = binding.value } } } } </script>
Always clean up event listeners or timers in the unmounted hook to avoid memory leaks.
Use binding.value to get the value passed to the directive.
Directives are great for DOM-related tasks that don't fit well in components.
Custom directives add reusable behavior to HTML elements.
Use lifecycle hooks like mounted and updated to control behavior.
Directives help keep your templates clean and your code organized.
Practice
Solution
Step 1: Understand what directives do in Vue
Directives are special markers on elements that tell Vue to do something with that element.Step 2: Identify the role of custom directives
Custom directives let you add reusable behavior to elements, like focusing an input or changing styles dynamically.Final Answer:
To add reusable behavior to HTML elements -> Option AQuick Check:
Custom directives = reusable element behavior [OK]
- Confusing directives with components
- Thinking directives manage app state
- Assuming directives handle routing
v-focus in Vue 3?Solution
Step 1: Recall Vue 3 global directive registration
In Vue 3, you use the app instance's directive method with the directive name without the 'v-' prefix.Step 2: Check the lifecycle hook and syntax
The correct hook for when the element is inserted is 'mounted', and the function receives the element as argument.Final Answer:
app.directive('focus', { mounted(el) { el.focus() } }) -> Option BQuick Check:
Vue 3 global directive = app.directive('name', { mounted }) [OK]
- Including 'v-' prefix in directive name
- Using Vue.directive instead of app.directive in Vue 3
- Using deprecated hooks like 'bind'
app.directive('color', {
mounted(el, binding) {
el.style.color = binding.value
},
updated(el, binding) {
el.style.color = binding.value
}
})
What will be the text color of the paragraph after the component updates if used as <p v-color="'red'">Hello</p> and later the binding value changes to 'blue'?Solution
Step 1: Understand directive lifecycle hooks
The 'mounted' hook sets the color initially, and the 'updated' hook runs when the binding value changes.Step 2: Trace the color change on update
When the binding value changes to 'blue', the 'updated' hook sets the element's color style to 'blue'.Final Answer:
The text color will change to blue -> Option CQuick Check:
updated hook changes color to new binding value [OK]
- Assuming color stays as initial value
- Ignoring the updated lifecycle hook
- Thinking directive causes errors on update
app.directive('tooltip', {
mounted(el, binding) {
el.setAttribute('title', binding.value)
},
updated(el, binding) {
el.setAttribute('title', binding.oldValue)
}
})
What is the problem with this directive when the binding value changes?Solution
Step 1: Analyze the updated hook usage
The updated hook sets the title attribute to binding.oldValue, which is the previous value, not the new one.Step 2: Understand the effect on the tooltip
Because it sets the old value on update, the tooltip does not reflect the new binding value after change.Final Answer:
The tooltip title does not update to the new value -> Option AQuick Check:
updated hook must use binding.value, not binding.oldValue [OK]
- Using binding.oldValue instead of binding.value on update
- Assuming no update needed for title
- Confusing syntax error with logic error
v-auto-focus that automatically focuses an input element only when it is inserted into the DOM and not on updates. Which is the best way to implement this directive in Vue 3?Solution
Step 1: Identify when to focus the element
The input should be focused only once when inserted, so the 'mounted' hook is the right place.Step 2: Avoid focusing on updates
Calling focus in 'updated' would focus repeatedly, which is not desired.Step 3: Understand Vue 3 lifecycle hooks
There is no 'created' hook for directives; 'mounted' is the earliest for DOM access.Final Answer:
Use the mounted hook to call el.focus() and leave updated empty -> Option DQuick Check:
Focus on mounted only, not updated [OK]
- Focusing in updated hook causing repeated focus
- Using non-existent created hook for directives
- Calling focus multiple times unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
