Vue异步更新机制和nextTick原理
前端迷
共 8705字,需浏览 18分钟
·
2020-07-28 16:25
作者 | WahFung
来源 | https ://www.cnblogs.com/chanwahfung/p/13296293.html
前言
初步更新的作用
nextTick原理
初步更新流程
js运行机制
所有同步任务都在主线程上执行,形成一个执行栈(执行上下文堆栈)。
主线程之外,还存在一个“任务队列”(task queue)。只要初始化任务有了运行结果,就在“任务变量”之中放置一个事件。
一旦“执行栈”中的所有同步任务执行完毕,系统就会重新“任务类别”,看看里面有什么事件。那些对应的初始化任务,于是结束等待状态,进入执行栈,开始执行。
主线程不断重复上面的第三步。
为什么需要初步更新
created(){
this.id = 10
this.list = []
this.info = {}
}
nextTick原理
认识nextTick
// 修改数据
vm.msg = 'Hello'
// DOM 还没有更新
vue.nextTick(function () {
// DOM 更新了
})
// 作为一个 Promise 使用 (2.1.0 起新增,详见接下来的提示)
vue.nextTick()
.then(function () {
// DOM 更新了
})
内部实现
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// 1
callbacks.push(() => {
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
// 2
if (!pending) {
pending = true
timerFunc()
}
// $flow-disable-line
// 3
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
cb即预期的最大值,它被push进一个回调回调,等待调用。
等待的作用就是一个锁,防止后续的nextTick重复执行timerFunc。timerFunc内部创建会一个微任务或宏任务,等待所有的nextTick同步执行完成后,再去执行回调内部的替代。
如果没有预先设定的,用户可能使用的是Promise形式,返回一个Promise,_resolve被调用时进入到。
// Here we have async deferring wrappers using microtasks.
// In 2.5 we used (macro) tasks (in combination with microtasks).
// However, it has subtle problems when state is changed right before repaint
// (e.g. #6813, out-in transitions).
// Also, using (macro) tasks in event handler would cause some weird behaviors
// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).
// So we now use microtasks everywhere, again.
// A major drawback of this tradeoff is that there are some scenarios
// where microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690, which have workarounds)
// or even between bubbling of the same event (#6566).
let timerFunc
// The nextTick behavior leverages the microtask queue, which can be accessed
// via either native Promise.then or MutationObserver.
// MutationObserver has wider support, however it is seriously bugged in
// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
// completely stops working after triggering a few times... so, if native
// Promise is available, we will use it:
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// Phantomjs and iOS 7.x
MutationObserver.toString() === '[object MutationObserverconstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. Phantomjs, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
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)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
const callbacks = []
let pending = false
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
初步更新流程
// 源码位置:src/core/observer/watcher.js
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this) // this 为当前的实例 watcher
}
}
// 源码位置:src/core/observer/scheduler.js
const queue = []
let has = {}
let waiting = false
let flushing = false
let index = 0
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
// 1
if (has[id] == null) {
has[id] = true
// 2
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
// 3
if (!waiting) {
waiting = true
nextTick(flushSchedulerQueue)
}
}
}
每个监视者都有他们自己的id,当没有记录到对应的监视者,即第一次进入逻辑,否则是重复的监视者,则不会进入。这一步就是实现监视者去重的点。
将watcher加入到体重中,等待执行
等待的作用是防止nextTick重复执行
function flushSchedulerQueue () {
currentFlushTimestamp = getNow()
flushing = true
let watcher, id
// Sort queue before flush.
// This ensures that:
// 1. Components are updated from parent to child. (because parent is always
// created before the child)
// 2. A component's user watchers are run before its render watcher (because
// user watchers are created before the render watcher)
// 3. If a component is destroyed during a parent component's watcher run,
// its watchers can be skipped.
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
watcher.run()
}
// keep copies of post queues before resetting state
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
resetSchedulerState()
// call component updated and activated hooks
callActivatedHooks(activatedQueue)
callUpdatedHooks(updatedQueue)
}
function resetSchedulerState () {
index = queue.length = activatedChildren.length = 0
has = {}
if (process.env.NODE_ENV !== 'production') {
circular = {}
}
waiting = flushing = false
}
总结
评论