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>
相信會(huì)用 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ù)之后
在看源碼之前,先來搞明白一個(gè)問題,為什么我們?cè)谛薷臄?shù)據(jù)之后,并沒有拿到最新的 dom 呢?
Vue 在更新 DOM 時(shí)是異步執(zhí)行的。只要偵聽到數(shù)據(jù)變化,Vue 將開啟一個(gè)隊(duì)列,并緩沖在同一事件循環(huán)中發(fā)生的所有數(shù)據(jù)變更。如果同一個(gè) watcher 被多次觸發(fā),只會(huì)被推入到隊(duì)列中一次。這種在緩沖時(shí)去除重復(fù)數(shù)據(jù)對(duì)于避免不必要的計(jì)算和 DOM 操作是非常重要的。然后,在下一個(gè)的事件循環(huán)“tick”中,Vue 刷新隊(duì)列并執(zhí)行實(shí)際 (已去重的) 工作。Vue 在內(nèi)部對(duì)異步隊(duì)列嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執(zhí)行環(huán)境不支持,則會(huì)采用 setTimeout(fn, 0) 代替。
以上是 vue 官網(wǎng)上給出的解釋,第一句話是重點(diǎn),解答了上面提出的那個(gè)問題,因?yàn)?dom 更新是異步的,但是我們的代碼卻是同步執(zhí)行的,也就是說數(shù)據(jù)改變之后,dom 不是同步改變的,所以我們不能直接拿到最新的 dom。下面就從源碼里來看 dom 是何時(shí)更新的,以及我們?yōu)槭裁从昧?$nextTick 就可以拿到最新的 dom。
首先這個(gè)問題的起因是數(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()
}
})
// ...
}
這個(gè)方法就是用來做響應(yīng)式的,多余的代碼刪了一些,這里只看這個(gè) Object.defineProperty,數(shù)據(jù)改變之后會(huì)觸發(fā) set,然后 set 里面,中間的一大堆都不看,看最后一行 dep.notify(),這個(gè)就是用來數(shù)據(jù)改變之后發(fā)布通知的,觀察者模式嘛,都懂的哈,然后就接著來看這個(gè) notify 方法里面做了什么,不用再找這個(gè) 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 方法
這個(gè) Dep 類就是用來收集響應(yīng)式依賴并且發(fā)布通知的,看 notify 方法,遍歷了所有的依賴,并且挨個(gè)觸發(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)
}
}
// ...
}
這個(gè) Watcher 類可以理解為就是一個(gè)偵聽 器或者說是觀察者,每個(gè)響應(yīng)式數(shù)據(jù)都會(huì)對(duì)應(yīng)的有一個(gè) watcher 實(shí)例,當(dāng)數(shù)據(jù)改變之后,就會(huì)通知到它,上面那個(gè) Dep 收集的就是他,看里面的這個(gè) update 方法,我們沒用 lazy 和 sync,所以進(jìn)來之后執(zhí)行的是那個(gè) 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)
}
}
}
可以看到這個(gè)方法接收的是一個(gè) watcher 實(shí)例,方法里面首先判斷了傳進(jìn)來的 watcher 是否已經(jīng)傳過了,忽略重復(fù)觸發(fā)的 watcher,沒有傳過就把它 push 到隊(duì)列中,然后下面看注釋也知道是要更新隊(duì)列,把一個(gè) flushSchedulerQueue 方法傳到了 nextTick 方法里面,這個(gè) flushSchedulerQueue 方法里面大概就是更新 dom 的邏輯了,再接著看 nextTick 方法里面是怎么執(zhí)行傳進(jìn)去的這個(gè)更新方法的
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
})
}
}
我們?cè)谕饷嬲{(diào)用的 $nextTick 方法其實(shí)就是這個(gè)方法了,方法里面先把傳進(jìn)來的 callback 存起來,然后下面又執(zhí)行了一個(gè) timerFunc 方法,看下這個(gè) 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]()
}
}
這一堆代碼就是異步處理更新隊(duì)列的邏輯了,在下一個(gè)的事件循環(huán)“tick”中,去刷新隊(duì)列,依次嘗試使用原生的 Promise.then、MutationObserver 和 setImmediate,如果執(zhí)行環(huán)境都不支持,則會(huì)采用 setTimeout(fn, 0) 代替。
然后再回到最初的問題,為什么用了 $nextTick 就可以獲取到最新的 dom 了 ?
我們?cè)賮硎崂硪槐樯厦鎻臄?shù)據(jù)變更到 dom 更新之前的整個(gè)流程
- 修改響應(yīng)式數(shù)據(jù)
- 觸發(fā)
Object.defineProperty中的set - 發(fā)布通知
- 觸發(fā)
Watcher中的update方法, update方法中把Watcher緩沖到一個(gè)隊(duì)列- 刷新隊(duì)列的方法(其實(shí)就是更新 dom 的方法)傳到
nextTick方法中 nextTick方法中把傳進(jìn)來的callback都放在一個(gè)數(shù)組callbacks中,然后放在異步隊(duì)列中去執(zhí)行
然后這時(shí)你調(diào)用了 $nextTick 方法,傳進(jìn)來一個(gè)獲取最新 dom 的回調(diào),這個(gè)回調(diào)也會(huì)推到那個(gè)數(shù)組 callbacks 中,此時(shí)遍歷 callbacks 并執(zhí)行所有回調(diào)的動(dòng)作已經(jīng)放到了異步隊(duì)列中,到這(假設(shè)你后面沒有其他的代碼了)所有的同步代碼就執(zhí)行完了,然后開始執(zhí)行異步隊(duì)列中的任務(wù),更新 dom 的方法是最先被推進(jìn)去的,所以就先執(zhí)行,你傳進(jìn)來的獲取最新 dom 的回調(diào)是最后傳進(jìn)來的所以最后執(zhí)行,顯而易見,當(dāng)執(zhí)行到你的回調(diào)的時(shí)候,前面更新 dom 的動(dòng)作都已經(jīng)完成了,所以現(xiàn)在你的回調(diào)就能獲取到最新的 dom 了。
以上就是Vue $nextTick 為什么能獲取到最新Dom源碼解析的詳細(xì)內(nèi)容,更多關(guān)于Vue $nextTick獲取最新Dom的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue——解決報(bào)錯(cuò) Computed property "****" was assigned to but it ha
這篇文章主要介紹了Vue——解決報(bào)錯(cuò) Computed property "****" was assigned to but it has no setter.的方法,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下2020-12-12
vue項(xiàng)目在webpack2實(shí)現(xiàn)移動(dòng)端字體自適配功能
這篇文章主要介紹了vue項(xiàng)目在webpack2實(shí)現(xiàn)移動(dòng)端字體自適配的相關(guān)知識(shí),本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-06-06
vue 輸入框輸入任意內(nèi)容返回?cái)?shù)字的實(shí)現(xiàn)
本文主要介紹了vue 輸入框輸入任意內(nèi)容返回?cái)?shù)字的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-03-03
Vue+Typescript中在Vue上掛載axios使用時(shí)報(bào)錯(cuò)問題
這篇文章主要介紹了Vue+Typescript中在Vue上掛載axios使用時(shí)報(bào)錯(cuò)問題,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-08-08
vue.js中window.onresize的超詳細(xì)使用方法
這篇文章主要給大家介紹了關(guān)于vue.js中window.onresize的超詳細(xì)使用方法,window.onresize 是直接給window的onresize屬性綁定事件,只能有一個(gè),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
vue項(xiàng)目如何使用$router.go(-1)返回時(shí)刷新原來的界面
這篇文章主要介紹了vue項(xiàng)目如何使用$router.go(-1)返回時(shí)刷新原來的界面問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Vue+OpenLayer實(shí)現(xiàn)測距功能
OpenLayers?是一個(gè)專為Web?GIS?客戶端開發(fā)提供的JavaScript?類庫包,用于實(shí)現(xiàn)標(biāo)準(zhǔn)格式發(fā)布的地圖數(shù)據(jù)訪問。本文將通過Vue和OpenLayer實(shí)現(xiàn)測距功能?,需要的可以參考一下2022-04-04
使用vue引入maptalks地圖及聚合效果的實(shí)現(xiàn)
這篇文章主要介紹了使用vue引入maptalks地圖及聚合效果的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-08-08

