Introduction
Custom directives let you add special behavior to HTML elements easily. They help you reuse code and keep your templates clean.
Custom directives let you add special behavior to HTML elements easily. They help you reuse code and keep your templates clean.
app.directive('directive-name', { mounted(el, binding) { // code to run when element is added to DOM }, updated(el, binding) { // code to run when element updates } })
app.directive('focus', {
mounted(el) {
el.focus()
}
})<input v-focus />
This Vue app uses a custom directive 'v-focus' to automatically put the cursor inside the input box when the page loads.
import { createApp } from 'vue' const app = createApp({ template: `<input v-focus placeholder='Focus me automatically' />` }) app.directive('focus', { mounted(el) { el.focus() } }) app.mount('#app')
Custom directives are great for DOM tasks that Vue's template syntax can't handle directly.
Keep directives focused on one job to make them easy to reuse and maintain.
Custom directives add reusable behaviors to HTML elements.
They help keep your Vue components clean and simple.
Use them when you need direct DOM control or special effects.
focus in Vue 3?app.directive(name, definition) to register directives globally.app.directive with a proper object containing mounted hook. Others use wrong methods or syntax.app.directive('highlight', {
mounted(el) {
el.style.backgroundColor = 'yellow'
}
})<div v-highlight>Text</div> in your template?mounted hook runs when the element is inserted, setting backgroundColor to yellow.v-highlight applies the directive, so the div's background becomes yellow, not border or text color.app.directive('scroll', {
mounted(el) {
window.addEventListener('scroll', () => {
el.textContent = window.scrollY
})
},
unmounted() {
window.removeEventListener('scroll')
}
})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?el.offsetParent !== null confirms the element is visible (not hidden by CSS).Pass the test and this pattern moves unknown