vue中dom的更像並非實時的,當數據改變後,vue會把渲染watcher添加到異步隊列,異步執行,同步代碼執行完成後再統一修改dom,咱們看下面的代碼。javascript
<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,在下一次事件循環中獲取。html
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
this.$nextTick(() => {
console.log(box.innerHTML) // world
})
複製代碼
若是咱們須要獲取數據更新後的dom信息,好比動態獲取寬高、位置信息等,須要使用nextTick。前端
vue雙向數據綁定依賴於ES5的Object.defineProperty,在數據初始化的時候,經過Object.defineProperty爲每個屬性建立getter與setter,把數據變成響應式數據。對屬性值進行修改操做時,如this.msg = world,實際上會觸發setter。下面看源碼,爲方便越讀,源碼有刪減。vue
數據改變觸發set函數java
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// 數據修改後觸發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() // 執行dep notify方法
}
})
複製代碼
執行dep.notify方法react
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++) {
// 實際上遍歷執行了subs數組中元素的update方法
subs[i].update()
}
}
}
複製代碼
當數據被引用時,如<div>{{msg}}</div>
,會執行get方法,並向subs數組中添加渲染Watcher,當數據被改變時執行Watcher的update方法執行數據更新。數組
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this) //執行queueWatcher
}
}
複製代碼
update 方法最終執行queueWatcherbash
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只執行一次
waiting = true
// 最終queueWatcher 方法會把flushSchedulerQueue 傳入到nextTick中執行
nextTick(flushSchedulerQueue)
}
}
}
複製代碼
執行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
// 遍歷執行渲染watcher的run方法 完成視圖更新
watcher.run()
}
// 重置waiting變量
resetSchedulerState()
...
}
複製代碼
也就是說當數據變化最終會把flushSchedulerQueue傳入到nextTick中執行flushSchedulerQueue函數會遍歷執行watcher.run()方法,watcher.run()方法最終會完成視圖更新,接下來咱們看關鍵的nextTick方法究竟是啥dom
nextTick方法會被傳進來的回調push進callbacks數組,而後執行timerFunc方法
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// push進callbacks數組
callbacks.push(() => {
cb.call(ctx)
})
if (!pending) {
pending = true
// 執行timerFunc方法
timerFunc()
}
}
複製代碼
timerFunc
let timerFunc
// 判斷是否原生支持Promise
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
// 若是原生支持Promise 用Promise執行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執行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執行flushCallbacks
setImmediate(flushCallbacks)
}
// 都不支持的狀況下使用setTimeout 0
} else {
timerFunc = () => {
// 使用setTimeout執行flushCallbacks
setTimeout(flushCallbacks, 0)
}
}
// flushCallbacks 最終執行nextTick 方法傳進來的回調函數
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
複製代碼
nextTick會優先使用microTask, 其次是macroTask 。
也就是說nextTick中的任務,實際上會異步執行,nextTick(callback)相似於 Promise.resolve().then(callback),或者setTimeout(callback, 0)。
也就是說vue的視圖更新 nextTick(flushSchedulerQueue)等同於setTimeout(flushSchedulerQueue, 0),會異步執行flushSchedulerQueue函數,因此咱們在this.msg = hello 並不會當即更新dom。
要想在dom更新後讀取dom信息,咱們須要在本次異步任務建立以後建立一個異步任務。
爲了驗證這個想法咱們不用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 ,那麼咱們添加的異步任務會在渲染的異步任務以前執行,拿不到更新後的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] } } 複製代碼
vue爲了保證性能,會把dom修改添加到異步任務,全部同步代碼執行完成後再統一修改dom,一次事件循環中的屢次數據修改只會觸發一次watcher.run()。也就是經過nextTick,nextTick會優先使用microTask建立異步任務。vue項目中若是須要獲取修改後的dom信息,須要經過nextTick在dom更新任務以後建立一個異步任務。如官網所說,nextTick會在下次 DOM 更新循環結束以後執行延遲迴調。