共计 5770 个字符,预计需要花费 15 分钟才能阅读完成。
Vue.nextTick 的应用场景
Vue 是采用异步的方式执行 DOM 更新。只要观察到数据变化,Vue 将开启一个队列,并缓冲同一事件循环中发生的所有数据改变。然后,在下一个的事件循环中,Vue 刷新队列并执行页面渲染工作。所以修改数据后 DOM 并不会立刻被重新渲染,如果想在数据更新后对页面执行 DOM 操作,可以在数据变化之后立即使用 Vue.nextTick(callback)。
下面这一段摘自 vue 官方文档,关于 JS 运行机制的说明:
JS 执行是单线程的,它是基于事件循环的。事件循环大致分为以下几个步骤:
(1)所有同步任务都在主线程上执行,形成一个执行栈(execution context stack)。
(2)主线程之外,还存在一个 ” 任务队列 ”(task queue)。只要异步任务有了运行结果,就在 ” 任务队列 ” 之中放置一个事件。
(3)一旦 ” 执行栈 ” 中的所有同步任务执行完毕,系统就会读取 ” 任务队列 ”,看看里面有哪些事件。那些对应的异步任务,于是结束等待状态,进入执行栈,开始执行。
(4)主线程不断重复上面的第三步。
在主线程中执行修改数据这一同步任务,DOM 的渲染事件就会被放到“任务队列”中,当“执行栈”中同步任务执行完毕,本次事件循环结束,系统才会读取并执行“任务队列”中的页面渲染事件。而 Vue.nextTick 中的回调函数则会在页面渲染后才执行。
例子如下:
<template>
<div>
<div ref="test">{{test}}</div>
</div>
</template>
// Some code...
data () {
return {test: 'begin'};
},
// Some code...
this.test = 'end';
console.log(this.$refs.test.innerText);//"begin"
this.nextTick(() => {console.log(this.$refs.test.innerText) //"end"
})
Vue.nextTick 实现原理
Vue.nextTick 的源码 vue 项目 /src/core/util/ 路径下的 next-tick.js 文件,文章最后也会贴出完整的源码
我们先来看看对于异步调用函数的实现方法:
let timerFunc
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)
}
}
这段代码首先的检测运行环境的支持情况,使用不同的异步方法。优先级依次是 Promise、MutationObserver、setImmediate 和 setTimeout。这是根据运行效率来做优先级处理,有兴趣可以去了解一下这几种方法的差异。总的来说,Event Loop 分为宏任务以及微任务,宏任务耗费的时间是大于微任务的,所以优先使用微任务。例如 Promise 属于微任务,而 setTimeout 就属于宏任务。最终 timerFunc 则是我们调用 nextTick 函数时要内部会调用的主要方法,那么 flushCallbacks 又是什么呢,我们在看看 flushCallbacks 函数:
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {copies[i]()}
}
这个函数比较简单,就是依次调用 callbacks 数组里面的方法。还使用 slice()方法复制 callbacks 数组并把 callbacks 数组清空,这里的 callbacks 数组就是存放主线程执行过程中的 Vue.nextTick()函数所传的回调函数集合(主线程可能会多次使用 Vue.nextTick()方法)。到这里就已经实现了根据环境选择异步方法,并在异步方法中依次调用传入 Vue.nextTick()方法的回调函数。nextTick 函数主要就是要将 callback 函数存在数组 callbacks 中,并调用 timerFunc 方法:
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。另外如果参数一的条件判断为 false 时则返回一个 Promise 对象。例如
Vue.nextTick(null, {value: 'test'})
.then((data) => {console.log(data.value) // 'test'
})
这里还使用了一个优化技巧,用 pending 来标记异步任务是否被调用,也就是说在同一个 tick 内只调用一次 timerFunc 函数,这样就不会开启多个异步任务。
完整的源码:
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.
// Techinically 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
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {_resolve = resolve})
}
}