众所周知,为了与浏览器进行交互,Javascript是一门非阻塞单线程脚本语言。vue
用一张图展现这个过程:ios
在实际状况中,上述的任务队列(task queue)中的异步任务分为两种:微任务(micro task)和宏任务(macro task)。git
microtask和macotask执行规则:github
下面来个简单例子:web
console.log(1);promise
setTimeout(function() {浏览器
console.log(2);app
}, 0);dom
new Promise(function(resolve,reject){异步
console.log(3)
resolve()
}).then(function() {
console.log(4);
}).then(function() {
console.log(5);
});
console.log(6);
一步一步分析以下:
1.同步代码做为第一个macrotask,按顺序输出:1 3 6
2.microtask按顺序执行:4 5
3.microtask清空后执行下一个macrotask:2
再来一个复杂的例子:
// Let's get hold of those elements
var outer = document.querySelector('.outer');
var inner = document.querySelector('.inner');
// Let's listen for attribute changes on the
// outer element
new MutationObserver(function() {
console.log('mutate');
}).observe(outer, {
attributes: true
});
// Here's a click listener…
function onClick() {
console.log('click');
setTimeout(function() {
console.log('timeout');
}, 0);
Promise.resolve().then(function() {
console.log('promise');
});
outer.setAttribute('data-random', Math.random());
}
// …which we'll attach to both elements
inner.addEventListener('click', onClick);
outer.addEventListener('click', onClick);
假设咱们建立一个有里外两部分的正方形盒子,里外都绑定了点击事件,此时点击内部,代码会如何执行?一步一步分析以下:
在 Vue.js 里是数据驱动视图变化,因为 JS 执行是单线程的,在一个 tick 的过程当中,它可能会屡次修改数据,但 Vue.js 并不会傻到每修改一次数据就去驱动一次视图变化,它会把这些数据的修改所有 push 到一个队列里,而后内部调用 一次 nextTick 去更新视图,因此数据到 DOM 视图的变化是须要在下一个 tick 才能完成。这即是咱们为何须要vue.nextTick.
这样一个功能和事件循环很是类似,在每一个 task 运行完之后,UI 都会重渲染,那么很容易想到在 microtask 中就完成数据更新,当前 task 结束就能够获得最新的 UI 了。反之若是新建一个 task 来作数据更新,那么渲染就会进行两次。
因此在vue 2.4以前使用microtask实现nextTick,直接上源码
var counter = 1var observer = new MutationObserver(nextTickHandler)var textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
能够看到使用了MutationObserver
然而到了vue 2.4以后却混合�使用microtask macrotask来实现,源码以下
/* @flow *//* globals MessageChannel */
import { noop } from 'shared/util'import { handleError } from './error'import { isIOS, isNative } from './env'
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 both micro and macro tasks.// In < 2.4 we used micro tasks everywhere, but there are some scenarios where// micro tasks have too high a priority and fires in between supposedly// sequential events (e.g. #4521, #6690) or even between bubbling of the same// event (#6566). However, using macro tasks everywhere also has subtle problems// when state is changed right before repaint (e.g. #6813, out-in transitions).// Here we use micro task by default, but expose a way to force macro task when// needed (e.g. in event handlers attached by v-on).let microTimerFunclet macroTimerFunclet useMacroTask = false
// Determine (macro) Task defer implementation.// Technically setImmediate should be the ideal choice, but it's only available// in IE. The only polyfill that consistently queues the callback after all DOM// events triggered in the same loop is by using MessageChannel./* istanbul ignore if */if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
macroTimerFunc = () => {
setImmediate(flushCallbacks)
}
} else if (typeof MessageChannel !== 'undefined' && (
isNative(MessageChannel) ||
// PhantomJS
MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
const channel = new MessageChannel()
const port = channel.port2
channel.port1.onmessage = flushCallbacks
macroTimerFunc = () => {
port.postMessage(1)
}
} else {
/* istanbul ignore next */
macroTimerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
// Determine MicroTask defer implementation./* istanbul ignore next, $flow-disable-line */if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
microTimerFunc = () => {
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)
}
} else {
// fallback to macro
microTimerFunc = macroTimerFunc
}
/**
* Wrap a function so that if any code inside triggers state change,
* the changes are queued using a Task instead of a MicroTask.
*/export function withMacroTask (fn: Function): Function {
return fn._withTask || (fn._withTask = function () {
useMacroTask = true
const res = fn.apply(null, arguments)
useMacroTask = false
return res
})
}
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
if (useMacroTask) {
macroTimerFunc()
} else {
microTimerFunc()
}
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
能够看到使用setImmediate、MessageChannel等mascrotask事件来实现nextTick。
为何会如此修改,其实看以前的事件冒泡例子就能够知道,因为microtask优先级过高,甚至会比冒泡快,因此会形成一些诡异的bug。如 issue #4521、#6690、#6556;可是若是所有都改为 macro task,对一些有重绘和动画的场景也会有性能影响,如 issue #6813。因此最终 nextTick 采起的策略是默认走 micro task,对于一些 DOM 交互事件,如 v-on 绑定的事件回调函数的处理,会强制走 macro task。