Performance: Creating custom directives
Custom directives affect how the browser updates and manipulates the DOM, impacting rendering speed and interaction responsiveness.
app.directive('good-style', { updated(el, binding) { const size = binding.value + 'px'; const margin = binding.value / 2 + 'px'; el.style.cssText = `width: ${size}; height: ${size}; margin: ${margin};`; } });
app.directive('bad-style', { updated(el, binding) { el.style.width = binding.value + 'px'; el.style.height = binding.value + 'px'; el.style.margin = binding.value / 2 + 'px'; } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Multiple separate style changes in directive | Few nodes updated | Multiple reflows per update | Moderate paint cost | [X] Bad |
| Batch style changes with cssText in directive | Few nodes updated | Single reflow per update | Lower paint cost | [OK] Good |
v-focus in Vue 3?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'?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?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?Pass the test and this pattern moves unknown