Performance: Directive hooks (mounted, updated, unmounted)
Directive hooks affect how and when DOM updates happen, impacting rendering speed and responsiveness.
mounted(el) { el.style.color = 'red'; } updated(el, binding) { if (binding.oldValue !== binding.value) { el.style.color = binding.value; } }mounted(el) { el.style.color = 'red'; } updated(el) { el.style.color = 'red'; }| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Unconditional style update in updated hook | Multiple writes per update | Triggers reflow every update | High paint cost | [X] Bad |
| Conditional style update checking value change | Writes only on change | Reflow only when needed | Lower paint cost | [OK] Good |
mounted hook in a Vue directive do?mounted hookmounted hook runs once when the directive is first attached to the element in the DOM.updated hook runs on data or element changes, and unmounted runs when the directive is removed, so they do not match the description of mounted.unmounted hook in a Vue directive?unmounted.el and binding, so unmounted(el, binding) { /* code */ } is correct.const myDirective = {
mounted(el) {
console.log('Mounted')
},
updated(el) {
console.log('Updated')
},
unmounted(el) {
console.log('Unmounted')
}
}mounted runs once when directive attaches, updated runs on element or data changes, unmounted runs when directive is removed.updated hook runs, so both Mounted (once) and Updated (on change) will log.const directive = {
mounted(el) {
console.log('Mounted')
},
updated() {
console.log('Updated')
},
unmounted(el) {
console.log('Unmounted')
}
}updated hook is missing the el parameter.mounted and unmounted correctly have el parameter. The unmounted hook is correctly named.mounted.unmounted to remove the listener.Pass the test and this pattern moves unknown