vue源碼nextTick使用及原理解析
1 nextTick的使用
vue中dom的更像并不是實(shí)時(shí)的,當(dāng)數(shù)據(jù)改變后,vue會(huì)把渲染watcher添加到異步隊(duì)列,異步執(zhí)行,同步代碼執(zhí)行完成后再統(tǒng)一修改dom,我們看下面的代碼。
<template>
<div class="box">{{msg}}</div>
</template>
export default {
name: 'index',
data () {
return {
msg: 'hello'
}
},
mounted () {
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
console.log(box.innerHTML) // hello
}
}
可以看到,修改數(shù)據(jù)后并不會(huì)立即更新dom ,dom的更新是異步的,無法通過同步代碼獲取,需要使用nextTick,在下一次事件循環(huán)中獲取。
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
this.$nextTick(() => {
console.log(box.innerHTML) // world
})
如果我們需要獲取數(shù)據(jù)更新后的dom信息,比如動(dòng)態(tài)獲取寬高、位置信息等,需要使用nextTick。
2 數(shù)據(jù)變化dom更新與nextTick的原理分析
2.1 數(shù)據(jù)變化
vue雙向數(shù)據(jù)綁定依賴于ES5的Object.defineProperty,在數(shù)據(jù)初始化的時(shí)候,通過Object.defineProperty為每一個(gè)屬性創(chuàng)建getter與setter,把數(shù)據(jù)變成響應(yīng)式數(shù)據(jù)。對屬性值進(jìn)行修改操作時(shí),如this.msg = world,實(shí)際上會(huì)觸發(fā)setter。下面看源碼,為方便越讀,源碼有刪減。
雙向數(shù)據(jù)綁定

數(shù)據(jù)改變觸發(fā)set函數(shù)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// 數(shù)據(jù)修改后觸發(fā)set函數(shù) 經(jīng)過一系列操作 完成dom更新
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify() // 執(zhí)行dep notify方法
}
})
執(zhí)行dep.notify方法
export default class Dep {
constructor () {
this.id = uid++
this.subs = []
}
notify () {
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
// 實(shí)際上遍歷執(zhí)行了subs數(shù)組中元素的update方法
subs[i].update()
}
}
}
當(dāng)數(shù)據(jù)被引用時(shí),如<div>{{msg}}</div> ,會(huì)執(zhí)行g(shù)et方法,并向subs數(shù)組中添加渲染W(wǎng)atcher,當(dāng)數(shù)據(jù)被改變時(shí)執(zhí)行Watcher的update方法執(zhí)行數(shù)據(jù)更新。
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this) //執(zhí)行queueWatcher
}
}
update 方法最終執(zhí)行queueWatcher
function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
// 通過waiting 保證nextTick只執(zhí)行一次
waiting = true
// 最終queueWatcher 方法會(huì)把flushSchedulerQueue 傳入到nextTick中執(zhí)行
nextTick(flushSchedulerQueue)
}
}
}
執(zhí)行flushSchedulerQueue方法
function flushSchedulerQueue () {
currentFlushTimestamp = getNow()
flushing = true
let watcher, id
...
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
// 遍歷執(zhí)行渲染watcher的run方法 完成視圖更新
watcher.run()
}
// 重置waiting變量
resetSchedulerState()
...
}
也就是說當(dāng)數(shù)據(jù)變化最終會(huì)把flushSchedulerQueue傳入到nextTick中執(zhí)行flushSchedulerQueue函數(shù)會(huì)遍歷執(zhí)行watcher.run()方法,watcher.run()方法最終會(huì)完成視圖更新,接下來我們看關(guān)鍵的nextTick方法到底是啥
2.2 nextTick
nextTick方法會(huì)被傳進(jìn)來的回調(diào)push進(jìn)callbacks數(shù)組,然后執(zhí)行timerFunc方法
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// push進(jìn)callbacks數(shù)組
callbacks.push(() => {
cb.call(ctx)
})
if (!pending) {
pending = true
// 執(zhí)行timerFunc方法
timerFunc()
}
}
timerFunc
let timerFunc
// 判斷是否原生支持Promise
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
// 如果原生支持Promise 用Promise執(zhí)行flushCallbacks
p.then(flushCallbacks)
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
// 判斷是否原生支持MutationObserver
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
let counter = 1
// 如果原生支持MutationObserver 用MutationObserver執(zhí)行flushCallbacks
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
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
timerFunc = () => {
// 如果原生支持setImmediate 用setImmediate執(zhí)行flushCallbacks
setImmediate(flushCallbacks)
}
// 都不支持的情況下使用setTimeout 0
} else {
timerFunc = () => {
// 使用setTimeout執(zhí)行flushCallbacks
setTimeout(flushCallbacks, 0)
}
}
// flushCallbacks 最終執(zhí)行nextTick 方法傳進(jìn)來的回調(diào)函數(shù)
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
nextTick會(huì)優(yōu)先使用microTask, 其次是macroTask 。
也就是說nextTick中的任務(wù),實(shí)際上會(huì)異步執(zhí)行,nextTick(callback)類似于
Promise.resolve().then(callback),或者setTimeout(callback, 0)。
也就是說vue的視圖更新 nextTick(flushSchedulerQueue)等同于setTimeout(flushSchedulerQueue, 0),會(huì)異步執(zhí)行flushSchedulerQueue函數(shù),所以我們在this.msg = hello 并不會(huì)立即更新dom。
要想在dom更新后讀取dom信息,我們需要在本次異步任務(wù)創(chuàng)建之后創(chuàng)建一個(gè)異步任務(wù)。
異步隊(duì)列

為了驗(yàn)證這個(gè)想法我們不用nextTick,直接用setTimeout實(shí)驗(yàn)一下。如下面代碼,驗(yàn)證了我們的想法。
<template>
<div class="box">{{msg}}</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
msg: 'hello'
}
},
mounted () {
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
setTimeout(() => {
console.log(box.innerHTML) // world
})
}
}
如果我們在數(shù)據(jù)修改前nextTick ,那么我們添加的異步任務(wù)會(huì)在渲染的異步任務(wù)之前執(zhí)行,拿不到更新后的dom。
<template>
<div class="box">{{msg}}</div>
</template>
<script>
export default {
name: 'index',
data () {
return {
msg: 'hello'
}
},
mounted () {
this.$nextTick(() => {
console.log(box.innerHTML) // hello
})
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
}
}
3 總結(jié)
vue為了保證性能,會(huì)把dom修改添加到異步任務(wù),所有同步代碼執(zhí)行完成后再統(tǒng)一修改dom,一次事件循環(huán)中的多次數(shù)據(jù)修改只會(huì)觸發(fā)一次watcher.run()。也就是通過nextTick,nextTick會(huì)優(yōu)先使用microTask創(chuàng)建異步任務(wù)。
vue項(xiàng)目中如果需要獲取修改后的dom信息,需要通過nextTick在dom更新任務(wù)之后創(chuàng)建一個(gè)異步任務(wù)。如官網(wǎng)所說,nextTick會(huì)在下次 DOM 更新循環(huán)結(jié)束之后執(zhí)行延遲回調(diào)。
參考文章
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue項(xiàng)目中,main.js,App.vue,index.html的調(diào)用方法
今天小編就為大家分享一篇vue項(xiàng)目中,main.js,App.vue,index.html的調(diào)用方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
axios全局請求參數(shù)設(shè)置,請求及返回?cái)r截器的方法
下面小編就為大家分享一篇axios全局請求參數(shù)設(shè)置,請求及返回?cái)r截器的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
Vue父組件調(diào)用子組件函數(shù)實(shí)現(xiàn)
這篇文章主要介紹了Vue父組件調(diào)用子組件函數(shù)實(shí)現(xiàn),全文通過舉例子及代碼的形式進(jìn)行了一個(gè)簡單的介紹,希望大家能夠理解并且學(xué)習(xí)到其中知識(shí)2021-08-08
關(guān)于vue2強(qiáng)制刷新,解決頁面不會(huì)重新渲染的問題
今天小編就為大家分享一篇關(guān)于vue2強(qiáng)制刷新,解決頁面不會(huì)重新渲染的問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10
Vue自定義組件實(shí)現(xiàn)?v-model?的幾種方式
在?Vue?中,v-model?是一個(gè)常用的指令,用于實(shí)現(xiàn)表單元素和組件之間的雙向綁定,當(dāng)我們使用原生的表單元素時(shí),直接使用?v-model?是很方便的,本文給大家介紹了Vue自定義組件實(shí)現(xiàn)?v-model?的幾種方式,需要的朋友可以參考下2024-02-02

