Performance: onUpdated and onBeforeUpdate
These lifecycle hooks affect the rendering performance by running code before and after the DOM updates, impacting interaction responsiveness and visual stability.
import { onBeforeUpdate, onUpdated, nextTick } from 'vue'; onBeforeUpdate(() => { // minimal or no work here }); onUpdated(async () => { await nextTick(); // defer heavy work or use requestIdleCallback });
import { onBeforeUpdate, onUpdated } from 'vue'; onBeforeUpdate(() => { for (let i = 0; i < 1000000; i++) { /* heavy loop */ } }); onUpdated(() => { // heavy DOM queries or recalculations document.querySelectorAll('.item').forEach(el => { /* complex logic */ }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous work in onBeforeUpdate/onUpdated | Multiple DOM queries | Triggers multiple reflows | High paint cost due to layout thrashing | [X] Bad |
| Minimal work and deferred heavy tasks | No extra DOM queries during update | Single reflow per update cycle | Low paint cost, smooth rendering | [OK] Good |
onBeforeUpdate and onUpdated in Vue?onBeforeUpdate triggers just before Vue updates the DOM to reflect data changes.onUpdated triggers right after the DOM has been updated.onBeforeUpdate runs before the screen updates; onUpdated runs after. -> Option DonBeforeUpdate in a Vue 3 component?onBeforeUpdate as a named export, so use curly braces in import.onBeforeUpdate with a callback function to run code before update.count changes from 0 to 1?import { ref, onBeforeUpdate, onUpdated } from 'vue';
export default {
setup() {
const count = ref(0);
onBeforeUpdate(() => console.log('Before update:', count.value));
onUpdated(() => console.log('After update:', count.value));
return { count };
}
}onBeforeUpdate runs after reactive data updated (to 1) but before DOM updates, so count.value is 1.onUpdated timingonUpdated runs after DOM updates, count.value is 1.onBeforeUpdate and onUpdated? import { ref, onBeforeUpdate, onUpdated } from 'vue';
export default {
setup() {
const count = ref(0);
onBeforeUpdate = () => console.log('Before update');
onUpdated(() => console.log('After update'));
count.value++;
return { count };
}
}onBeforeUpdate instead of calling it with a callback.count.value++ is valid, and count is returned properly.score every time it updates in a Vue 3 component. Which approach correctly uses onBeforeUpdate and onUpdated to achieve this?import { ref, onBeforeUpdate, onUpdated } from 'vue';
export default {
setup() {
const score = ref(0);
let oldScore = 0;
onBeforeUpdate(() => {
oldScore = score.value;
});
onUpdated(() => {
console.log(`Score changed from ${oldScore} to ${score.value}`);
});
return { score };
}
}onBeforeUpdate runs after data updated, so sets oldScore to new value.onUpdated logs new value for both old and current.Pass the test and this pattern moves unknown