算法题-回溯
2026/7/30 12:51:33
Vue 的 DOM 更新是异步的(基于微任务队列)。当你修改数据后,Vue 不会立即更新 DOM,而是将更新推入一个队列,在下一个事件循环(tick)中批量执行。
nextTick() 允许你在 DOM 更新完成后执行回调函数,确保操作的是最新的 DOM。
this.message='Hello Vue!';// 修改数据Vue.nextTick(()=>{// DOM 已更新constel=document.getElementById('message');console.log(el.textContent);// 'Hello Vue!'});this.message='Hello Vue!';Vue.nextTick().then(()=>{constel=document.getElementById('message');console.log(el.textContent);// 'Hello Vue!'});exportdefault{methods:{updateMessage(){this.message='Updated!';this.$nextTick(()=>{console.log('DOM updated!');});}}}Vue 的 nextTick() 优先使用 微任务(Microtask) 实现(如 Promise.then、MutationObserver),在不支持微任务的环境中降级为 宏任务(Macrotask)(如 setTimeout)。
letcallbacks=[];letpending=false;functionnextTick(cb){callbacks.push(cb);if(!pending){pending=true;// 优先使用微任务if(typeofPromise!=='undefined'){Promise.resolve().then(flushCallbacks);}elseif(typeofMutationObserver!=='undefined'){// 使用 MutationObserver}else{// 降级为宏任务setTimeout(flushCallbacks,0);}}}functionflushCallbacks(){pending=false;constcopies=callbacks.slice();callbacks=[];copies.forEach(cb=>cb());}Vue 的 DOM 更新是异步的。直接操作 DOM 可能无法获取最新状态:
this.message='New Message';console.log(document.getElementById('msg').textContent);// 可能是旧值!Vue 3 的 nextTick 从 vue 包中导入:
import{nextTick}from'vue';asyncfunctionupdate(){state.message='Updated';awaitnextTick();console.log('DOM updated!');}exportdefault{data(){return{message:'Initial'};},methods:{asyncupdateMessage(){this.message='Updated';awaitthis.$nextTick();constel=document.getElementById('msg');console.log(el.textContent);// 'Updated'}}}this.items.push(newItem);this.$nextTick(()=>{this.scrollToBottom();});