Performance: Why custom directives matter
Custom directives affect how efficiently DOM manipulations happen and how often the browser must recalculate styles and layouts.
const highlightDirective = { mounted(el) { el.addEventListener('scroll', () => { el.style.backgroundColor = 'yellow'; }); } }; const app = Vue.createApp({}); app.directive('highlight', highlightDirective);
const app = Vue.createApp({ mounted() { const el = this.$refs.myElement; el.addEventListener('scroll', () => { el.style.backgroundColor = 'yellow'; }); } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct DOM manipulation in lifecycle hooks | High (multiple event handlers) | Multiple per event | High due to frequent style changes | [X] Bad |
| Using custom directives for DOM updates | Controlled and isolated | Single or minimal | Lower paint cost due to fewer style recalculations | [OK] Good |
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