Vue $nextTick 為什么能獲取到最新Dom源碼解析
正文
<template>
<p id='text'>{{text}}</p>
<button @click='change'>click</button>
</template>
<script>
export default {
data() {
return {
text: 'hello world'
}
}
methods: {
change() {
this.text = 'hello girl'
const textElement = document.getElementById('text')
console.log(textElement.innerHTML)
}
}
}
</script>
相信會用 Vue 的同學(xué)們應(yīng)該都知道,這里的 change 方法里面打印的 textElement.innerHTML 的值還是 hello world,并不是修改之后的 hello girl,如果想要輸出的是修改后的是 hello girl,就需要使用 $nextTick,像這樣
this.text = 'hello girl'
await this.$nextTick()
const textElement = document.getElementById('text')
console.log(textElement.innerHTML) // hello girl
// 或者這樣
this.$nextTick(() => {
const textElement = document.getElementById('text')
console.log(textElement.innerHTML) // hello girl
})
這樣就可以輸出 hello girl 了。
那么,為什么用了 $nextTick 就可以了呢,Vue 在背后做了哪些處理,接下來本文將從 Vue 的源碼深入了解 $nextTick 背后的原理。
修改數(shù)據(jù)之后
在看源碼之前,先來搞明白一個問題,為什么我們在修改數(shù)據(jù)之后,并沒有拿到最新的 dom 呢?
Vue 在更新 DOM 時是異步執(zhí)行的。只要偵聽到數(shù)據(jù)變化,Vue 將開啟一個隊列,并緩沖在同一事件循環(huán)中發(fā)生的所有數(shù)據(jù)變更。如果同一個 watcher 被多次觸發(fā),只會被推入到隊列中一次。這種在緩沖時去除重復(fù)數(shù)據(jù)對于避免不必要的計算和 DOM 操作是非常重要的。然后,在下一個的事件循環(huán)“tick”中,Vue 刷新隊列并執(zhí)行實際 (已去重的) 工作。Vue 在內(nèi)部對異步隊列嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執(zhí)行環(huán)境不支持,則會采用 setTimeout(fn, 0) 代替。
以上是 vue 官網(wǎng)上給出的解釋,第一句話是重點,解答了上面提出的那個問題,因為 dom 更新是異步的,但是我們的代碼卻是同步執(zhí)行的,也就是說數(shù)據(jù)改變之后,dom 不是同步改變的,所以我們不能直接拿到最新的 dom。下面就從源碼里來看 dom 是何時更新的,以及我們?yōu)槭裁从昧?$nextTick 就可以拿到最新的 dom。
首先這個問題的起因是數(shù)據(jù)改變了,所以我們就直接從數(shù)據(jù)改變之后的代碼看
function defineReactive() {
// src/core/observer/index.js
// ...
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
// ...
}
這個方法就是用來做響應(yīng)式的,多余的代碼刪了一些,這里只看這個 Object.defineProperty,數(shù)據(jù)改變之后會觸發(fā) set,然后 set 里面,中間的一大堆都不看,看最后一行 dep.notify(),這個就是用來數(shù)據(jù)改變之后發(fā)布通知的,觀察者模式嘛,都懂的哈,然后就接著來看這個 notify 方法里面做了什么,不用再找這個 dep 了,直接快捷鍵跳轉(zhuǎn)函數(shù)定義,嗖一下,很快的
// src/core/observer/dep.js
class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
this.id = uid++
this.subs = []
}
// ...
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
subs.sort((a, b) => a.id - b.id)
}
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}
update 方法
這個 Dep 類就是用來收集響應(yīng)式依賴并且發(fā)布通知的,看 notify 方法,遍歷了所有的依賴,并且挨個觸發(fā)了他們的 update 方法,接著再看 update 方法
export default class Watcher {
// src/core/observer/watcher.js
// ...
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
// ...
}
這個 Watcher 類可以理解為就是一個偵聽 器或者說是觀察者,每個響應(yīng)式數(shù)據(jù)都會對應(yīng)的有一個 watcher 實例,當(dāng)數(shù)據(jù)改變之后,就會通知到它,上面那個 Dep 收集的就是他,看里面的這個 update 方法,我們沒用 lazy 和 sync,所以進(jìn)來之后執(zhí)行的是那個 queueWatcher 方法,
function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
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 = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
nextTick(flushSchedulerQueue)
}
}
}
可以看到這個方法接收的是一個 watcher 實例,方法里面首先判斷了傳進(jìn)來的 watcher 是否已經(jīng)傳過了,忽略重復(fù)觸發(fā)的 watcher,沒有傳過就把它 push 到隊列中,然后下面看注釋也知道是要更新隊列,把一個 flushSchedulerQueue 方法傳到了 nextTick 方法里面,這個 flushSchedulerQueue 方法里面大概就是更新 dom 的邏輯了,再接著看 nextTick 方法里面是怎么執(zhí)行傳進(jìn)去的這個更新方法的
nextTick 方法里面怎么執(zhí)行傳進(jìn)去更新方法
// src/core/util/next-tick.js
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
})
}
}
我們在外面調(diào)用的 $nextTick 方法其實就是這個方法了,方法里面先把傳進(jìn)來的 callback 存起來,然后下面又執(zhí)行了一個 timerFunc 方法,看下這個 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) ||
// PhantomJS and iOS 7.x
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 {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
這一堆代碼就是異步處理更新隊列的邏輯了,在下一個的事件循環(huán)“tick”中,去刷新隊列,依次嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執(zhí)行環(huán)境都不支持,則會采用 setTimeout(fn, 0) 代替。
然后再回到最初的問題,為什么用了 $nextTick 就可以獲取到最新的 dom 了 ?
我們再來梳理一遍上面從數(shù)據(jù)變更到 dom 更新之前的整個流程
- 修改響應(yīng)式數(shù)據(jù)
- 觸發(fā)
Object.defineProperty中的set - 發(fā)布通知
- 觸發(fā)
Watcher中的update方法, update方法中把Watcher緩沖到一個隊列- 刷新隊列的方法(其實就是更新 dom 的方法)傳到
nextTick方法中 nextTick方法中把傳進(jìn)來的callback都放在一個數(shù)組callbacks中,然后放在異步隊列中去執(zhí)行
然后這時你調(diào)用了 $nextTick 方法,傳進(jìn)來一個獲取最新 dom 的回調(diào),這個回調(diào)也會推到那個數(shù)組 callbacks 中,此時遍歷 callbacks 并執(zhí)行所有回調(diào)的動作已經(jīng)放到了異步隊列中,到這(假設(shè)你后面沒有其他的代碼了)所有的同步代碼就執(zhí)行完了,然后開始執(zhí)行異步隊列中的任務(wù),更新 dom 的方法是最先被推進(jìn)去的,所以就先執(zhí)行,你傳進(jìn)來的獲取最新 dom 的回調(diào)是最后傳進(jìn)來的所以最后執(zhí)行,顯而易見,當(dāng)執(zhí)行到你的回調(diào)的時候,前面更新 dom 的動作都已經(jīng)完成了,所以現(xiàn)在你的回調(diào)就能獲取到最新的 dom 了。
以上就是Vue $nextTick 為什么能獲取到最新Dom源碼解析的詳細(xì)內(nèi)容,更多關(guān)于Vue $nextTick獲取最新Dom的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue 中 element-ui table合并上下兩行相同數(shù)據(jù)單元格
這篇文章主要介紹了vue 中 element-ui table合并上下兩行相同數(shù)據(jù)單元格,本文通過實例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
Vue3 響應(yīng)式 API 及 reactive 和 ref&
響應(yīng)式是一種允許以聲明式的方式去適應(yīng)變化的編程范例,這篇文章主要介紹了關(guān)于Vue3響應(yīng)式API及reactive和ref的用法,需要的朋友可以參考下2023-06-06
Slots Emit和Props穿透組件封裝實現(xiàn)摸魚加鐘
這篇文章主要為大家介紹了Slots Emit和Props穿透組件封裝實現(xiàn)示例詳解,為摸魚加個鐘,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08

