Vue的官方文档中这么说的:“在下次 DOM 更新循环结束以后执行延迟回调。在修改数据以后当即使用这个方法,获取更新后的 DOM。”,为何会出现这么一个API?主要缘由是由于Vue在更新DOM采用的是异步执行的,只要侦听到数据变化,Vue将开启一个队列,并缓冲在同一个事件循环中发生的全部数据变动。node
虽然官方一直建议咱们使用数据驱动的方案去写代码,可是偶尔仍是不可避免的须要操做dom。ios
<div v-for='item of list' :key='item' class='list-item'>
{{ item }}
</div>
list = [1,2,3,4]
当咱们在mounted中往list中push一个数字的时候,马上获取class='list-item'元素的长度,拿到的依然是4,并无变成5。
由于Vue中DOm更新是异步,因此马上打印DOM并无更新,这时候经过nextTick才能正确的得到长度。
this.$nextTick(() => {
console.log(document.getElementByClassName('list-item').length)
})
复制代码
若是同一个 watcher 被屡次触发,只会被推入到队列中一次。这种在缓冲时去除重复数据对于避免没必要要的计算和 DOM 操做是很是重要的。而后,在下一个的事件循环“tick”中,Vue 刷新队列并执行实际 (已去重的) 工做,总的来讲就是去重,内部具体是什么样的,等我看了再告诉大家。segmentfault
咱们都是知道JS是单线程非阻塞的语言,这意味着主线程只能一次性执行一个任务 首先了解一下基本概念:微任务,宏任务,异步任务,同步任务。浏览器
微任务,microtask 又叫jobs,常见的有: 1.process.nextTick(node) 2.Promise 3.MutationObserver(HTML5新特性) 4.Messapp
宏任务,macroTask 又叫task,常见的有: 1.script(总体代码) 2.setTimeout 3.setInterval 4.setImmediate 5.I/O 6.UI render 7.MessageChanneldom
指的是,在主线程上排队执行的任务,只有前一个任务执行完毕,才能执行后一个任务,例如 1+2,典型的案例异步
function loop() {
while(true) {}
}
loop()
console.log(1)
复制代码
执行loop会占用主线程,进入无限循环,前面没执行完,后面的1一直不会被打印async
指的是,不进入主线程、而进入"任务队列"(task queue)的任务,只有等主线程任务执行完毕,"任务队列"开始通知主线程,请求执行任务,该任务才会进入主线程执行,ide
function loop () {
setTimeout(loop, 0);
}
loop()
复制代码
执行loop的时候。看似是一个无限循环的状态,可是实际上,不会致使页面卡死,依然能够作其余的事情,由于setTimeout是一个异步任务,他们执行完一次就会退出主线程。oop
这张图将浏览器的Event Loop完整的描述了出来,我来说执行一个JavaScript代码的具体流程 在执行一段代码的时候,先执行同步任务,再执行微任务,再执行宏任务;
1.执行全局Script同步代码,这些同步代码有一些是同步语句,有一些是异步语句(好比setTimeout等);
2.全局Script代码执行完毕后,调用栈Stack会清空;
3.从微队列microtask queue中取出位于队首的回调任务,放入调用栈Stack中执行,执行完后microtask queue长度减1;
4.继续取出位于队首的任务,放入调用栈Stack中执行,以此类推,直到直到把microtask queue中的全部任务都执行完毕。注意,若是在执行microtask的过程当中,又产生了microtask,那么会加入到队列的末尾,也会在这个周期被调用执行;
5.microtask queue中的全部任务都执行完毕,此时microtask queue为空队列,调用栈Stack也为空;
6.取出宏队列macrotask queue中位于队首的任务,放入Stack中执行;
7.执行完毕后,调用栈Stack为空; 重复第3-7个步骤;(event-loop)
前面说过了,由于Vue在更新DOM采用的是异步执行的,只要侦听到数据变化,Vue将开启一个队列,并缓冲在同一个事件循环中发生的全部数据变动。因此咱们只须要把要执行的callback放到微任务或者宏任务中去执行,就能够了。
按照这个思路咱们去看下Vue中的实现:
1.首先有个callbacks的队列 2.屡次使用nextTick只算一次,因此须要使用pending限制一下,不然页面看到的就是一个连续变化的过程,体验很很差 3.根据不一样的平台,浏览器环境,向下兼容,兜底方案是setTimeout 4.顺序是这样子的:Promise > MutationObserver > setImmediate > setTimeout
/* @flow */
/* globals MutationObserver */
import { noop } from 'shared/util'
import { handleError } from './error'
import { isIE, isIOS, isNative } from './env'
// 此处标记是否为微任务,会在其余模块中,对事件作特殊处理
export let isUsingMicroTask = false
// 回掉队列
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]()
}
}
// 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)
}
}
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
// 做为一个 Promise 使用 (2.1.0 起新增)
// 2.1.0 起新增:若是没有提供回调且在支持 Promise 的环境中,
// 则返回一个 Promise。请注意 Vue 不自带 Promise 的 polyfill,因此若是你的目标浏览器不原生支持 Promise (IE:大家都看我干吗),你得本身提供 polyfill。
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
复制代码
最后周末愉快