Performance: Why custom directives matter
MEDIUM IMPACT
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 |