一段代码
<div id="app">{{ msg }}</div>
<script type="text/javascript">
const vm = new Vue({
el: '#app',
data: {
msg: "a",
}
});
vm.msg = "b"
Promise.resolve().then(() => {
console.log('xxx')
})
vm.$nextTick(()=>{
console.log(vm.$el.innerHTML)
})
</script>
控制台依次打印: b xxx
- 为什么会先打印b再打印xxx呢?nextTick不也是优先用Promise实现的嘛?既然都是进微队列那么这个现象怎么解释?
vm.msg = "b"执行; 数据变化,页面要重新渲染,但vue为了提高渲染效率,使用异步更新dom的策略,而异步更新dom实现方式主要就是调用nextTick函数。nextTick内部通过Promise.resolve().then(flushCallbacks)的方式,把flushCallbacks函数推入微队列(flushCallbacks函数的作用就是遍历执行callbacks数组所有回调函数)。
也就是说,vm.msg = "b"执行完,微队列已经有flushCallbacks函数,当你手动调用nextTick时,可以简单认为只是把回调函数push进callbacks数组里。从微队列顺序来说,你写的$nextTick回调就在Promise回调之前执行了。
简单来说,是因为数据变动时,vue内部调用了nextTick函数(表面nextTick要晚些执行,实际人家在vm.msg="b"的时候就执行了)我们把vm.msg = "b"往后移下:
Promise.resolve().then(() => {
console.log('xxx')
})
vm.msg = "b"
vm.$nextTick(()=>{
console.log(vm.$el.innerHTML)
})
控制台依次打印: xxx b
当然,如果没有vm.msg = "b"这句,nextTick()就不会提前被调用,也是先输出xxx,再输出b。
-[扩展] 如果vm.$nextTick()不传参数,就可以当Promise使用
vm.$nextTick().then(() => {
console.log('aaaa');
})
下面附上源码,供大家学习参考:
- nextTick源码:
(位置:src/core/util/next-tick.js)
/* @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]()
}
}
let timerFunc
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
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}