前言
可能你还没有注意到,Vue 在更新 DOM 时是异步执行的。只要侦听到数据变化,Vue 将开启一个队列,并缓冲在同一事件循环中发生的所有数据变更。如果同一个 watcher 被多次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免不必要的计算和 DOM 操作是非常重要的。然后,在下一个的事件循环“tick”中,Vue 刷新队列并执行实际 (已去重的) 工作。Vue 在内部对异步队列尝试使用原生的 Promise.then、MutationObserver 和 setImmediate,如果执行环境不支持,则会采用 setTimeout(fn, 0) 代替。
思考题:
先打印什么?心中想好答案,我们正式开始分析nextTick
1.首先需要了解js的执行机制juejin.cn/post/684490…
2.直接看一下源码(src/core/observer/watcher.js)
// 1. 触发 Data.set
// 2. 调用 dep.notify
// 3. Dep 会遍历所有相关的 Watcher 执行 update 方法
class Watcher {
// 4. 执行更新操作
update() {
queueWatcher(this);
}
}
const queue = [];
function queueWatcher(watcher: Watcher) {
// 5. 将当前 Watcher 添加到异步队列
queue.push(watcher);
// 6. 执行异步队列,并传入回调
nextTick(flushSchedulerQueue);
}
// 更新视图的具体方法
function flushSchedulerQueue() {
let watcher, id;
// 排序,先渲染父节点,再渲染子节点
// 这样可以避免不必要的子节点渲染,如:父节点中 v-if 为 false 的子节点,就不用渲染了
queue.sort((a, b) => a.id - b.id);
// 遍历所有 Watcher 进行批量更新。
for (index = 0; index watcher = queue[index];
// 更新 DOM
watcher.run();
}
}
根据上面的代码,我们可以得出这样一个流程图:
图中可以看到,Vue 在调用 Watcher 更新视图时,并不会直接进行更新,而是把需要更新的 Watcher 加入到 Queue 队列里,然后把具体的更新方法 flushSchedulerQueue 传给 nextTick 进行调用
接下来,我们分析一下 nextTick
const callbacks = [];
let timerFunc;
function nextTick(cb?: Function, ctx?: Object) {
let _resolve;
// 1.将传入的 flushSchedulerQueue 方法添加到回调数组
callbacks.push(() => {
cb.call(ctx);
});
// 2.执行异步任务
// 此方法会根据浏览器兼容性,选用不同的异步策略
timerFunc();
}
可以看到,nextTick 函数非常简单,它只是将传入的 flushSchedulerQueue 添加到 callbacks 数组中,然后执行了 timerFunc 方法。
接下来,我们分析一下 timerFunc 方法。
let timerFunc;
// 判断是否兼容 Promise
if (typeof Promise !== "undefined") {
timerFunc = () => {
Promise.resolve().then(flushCallbacks);
};
// 判断是否兼容 MutationObserver
// https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
} else if (typeof MutationObserver !== "undefined") {
let counter = 1;
const observer = new MutationObserver(flushCallbacks);
const textNode = document.createTextNode(String(counter));
observer.observe(textNode, {
characterData: true,
});
timerFunc = () => {
counter = (counter + 1) % 2;
textNode.data = String(counter);
};
// 判断是否兼容 setImmediate
// 该方法存在一些 IE 浏览器中
} else if (typeof setImmediate !== "undefined") {
// 这是一个宏任务,但相比 setTimeout 要更好
timerFunc = () => {
setImmediate(flushCallbacks);
};
} else {
// 如果以上方法都不知道,使用 setTimeout 0
timerFunc = () => {
setTimeout(flushCallbacks, 0);
};
}
// 异步执行完后,执行所有的回调方法,也就是执行 flushSchedulerQueue
function flushCallbacks() {
for (let i = 0; i callbacks[i]();
}
}
可以看到,timerFunc 是根据浏览器兼容性创建的一个异步方法,它执行完成之后,会调用 flushSchedulerQueue 方法进行具体的 DOM 更新。 分析到这里,我们就可以得到一张整体的流程图了。
接下来,我们来完善一些判断逻辑。
-
has
是一个对象,用来过滤watcher。 当这个watcher 已经调用过更新函数,那么就在 has 中标记这个 id 也就是,你同时间调用多次 watcher.update ,其实只有第一次调用有用,后面的都会被过滤掉
-
waiting
为 true 表示已经把 【watcher 更新队列执行函数】 注册到宏微任务上了(或者说存放进 callbacks 中)。 正在等待JS栈为空后,就可以执行更新。直到所有watcher 更新完毕,才重置为 false
-
flushing
为 true 表示 watcher 更新队列正在执行更新(就是开始遍历 watcher 队列,逐个调用 watcher 更新了) 直到所有watcher 更新完毕,才重置为 false
结合以上判断,最终的流程图如下
最后,我们分析一下,为什么 this.$nextTick 能够获取更新后的 DOM?
// 我们使用 this.$nextTick 其实就是调用 nextTick 方法
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this);
};
可以看到,调用 this.nextTick 的回调函数时,能获取到更新后的 DOM 元素了。这也就回答了开头的问题了,为什么会先打印this.$nextTick的值。
思考与总结
- 修改 Vue 中的 Data 时,就会触发所有和这个 Data 相关的 Watcher 进行更新。
- 首先,会将所有的 Watcher 加入队列 Queue。
- 然后,调用 nextTick 方法,执行异步任务。
- 在异步任务的回调中,对 Queue 中的 Watcher 进行排序,然后执行对应的 DOM 更新。
扩展:
一开始的题目如何实现promise比nextTick先执行呢?(题目中代码顺序不变)
nextTick支持两种形式,一种是回调,一种是promise,具体哪种取决于你有没有传入回调函数
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
答案是: 改成this.$nextTick().then(...)
最后这个能清楚做出来 说明理解的差不多了
mounted() {
this.$nextTick().then(()=>{
console.log('nextTick');
})
Promise.resolve().then(()=>{
console.log('promise111');
}).then(()=>{
console.log('promise2222');
})
}