源码地址:https://github.com/vuejs/vue
模块路径:src\core\util\next-tick.js
问题:vue中的数据和界面更新是异步的,所以数据更新后dom不能立刻更新,那么想要获取到最新的dom数据,就需要nextTick帮我们实现
分析:
- 如果支持promise,则首先以promise的方式执行,但是界面更新是在微任务之后执行,所以用promise拿到的数据不是从界面获取的,而是从dom树上获取的,IOS的UIWebViews不支持promise
-
否则,如果不是IE浏览器并且支持MutationObserver,则以MutationObserver的方式执行,MutationObserver的作用是监听dom变化,dom更新后执行回调。MutationObserver在IE浏览器中会出现问题,所以在IE中不用这个API
-
否则,如果支持setImmediate,则使用setImmediate,setImmediate与setTimeout比起来效率更高,setImmediate会立即执行,没有延迟
-
否则以setTimeout(下下策)
核心代码:
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
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)) {
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
全部代码:
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 */
// 优先以promise处理,promise执行的时候界面还没有更新,数据更新后watcher会立即更新dom树
// 所以此时是从dom树上获取的最新数据(同步任务->微任务->更新界面->宏任务)
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)//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.
// IOS的UIWebViews控件不支持promise
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
// MutationObserver的作用是监听dom对象的改变,改变后会执行一个回调函数,也是个微任务(在IE11中有问题)
} 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
// 否则降级为setImmediate,setImmediate只有IE浏览器和Node支持
// 好处是setImmediate性能比setTimeout好,setTimeout设为0也需要等4ms,setImmediate会立即执行
} 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)
}
}
// cb是用户传过来的
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
callbacks.push(() => {//存储回调函数cb
if (cb) {
try {
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {//队列是否正在被处理
pending = true
timerFunc()//遍历callback数组,依次调用,重点!!!!
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
// 返回promise对象
return new Promise(resolve => {
_resolve = resolve
})
}
}