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

數據改變觸發(fā)set函數
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// 數據修改后觸發(fā)set函數 經過一系列操作 完成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++) {
// 實際上遍歷執(zhí)行了subs數組中元素的update方法
subs[i].update()
}
}
}
當數據被引用時,如<div>{{msg}}</div> ,會執(zhí)行get方法,并向subs數組中添加渲染Watcher,當數據被改變時執(zhí)行Watcher的update方法執(zhí)行數據更新。
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 方法會把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()
...
}
也就是說當數據變化最終會把flushSchedulerQueue傳入到nextTick中執(zhí)行flushSchedulerQueue函數會遍歷執(zhí)行watcher.run()方法,watcher.run()方法最終會完成視圖更新,接下來我們看關鍵的nextTick方法到底是啥
2.2 nextTick
nextTick方法會被傳進來的回調push進callbacks數組,然后執(zhí)行timerFunc方法
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// push進callbacks數組
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 方法傳進來的回調函數
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
nextTick會優(yōu)先使用microTask, 其次是macroTask 。
也就是說nextTick中的任務,實際上會異步執(zhí)行,nextTick(callback)類似于
Promise.resolve().then(callback),或者setTimeout(callback, 0)。
也就是說vue的視圖更新 nextTick(flushSchedulerQueue)等同于setTimeout(flushSchedulerQueue, 0),會異步執(zhí)行flushSchedulerQueue函數,所以我們在this.msg = hello 并不會立即更新dom。
要想在dom更新后讀取dom信息,我們需要在本次異步任務創(chuàng)建之后創(chuàng)建一個異步任務。
異步隊列

為了驗證這個想法我們不用nextTick,直接用setTimeout實驗一下。如下面代碼,驗證了我們的想法。
<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
})
}
}
如果我們在數據修改前nextTick ,那么我們添加的異步任務會在渲染的異步任務之前執(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 總結
vue為了保證性能,會把dom修改添加到異步任務,所有同步代碼執(zhí)行完成后再統一修改dom,一次事件循環(huán)中的多次數據修改只會觸發(fā)一次watcher.run()。也就是通過nextTick,nextTick會優(yōu)先使用microTask創(chuàng)建異步任務。
vue項目中如果需要獲取修改后的dom信息,需要通過nextTick在dom更新任務之后創(chuàng)建一個異步任務。如官網所說,nextTick會在下次 DOM 更新循環(huán)結束之后執(zhí)行延遲回調。
參考文章
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue項目中,main.js,App.vue,index.html的調用方法
今天小編就為大家分享一篇vue項目中,main.js,App.vue,index.html的調用方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09

