最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

vue源碼nextTick使用及原理解析

 更新時(shí)間:2019年08月13日 15:10:53   作者:fecoder  
這篇文章主要介紹了vue源碼nextTick使用及原理解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

1 nextTick的使用

vue中dom的更像并不是實(shí)時(shí)的,當(dāng)數(shù)據(jù)改變后,vue會把渲染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ù)后并不會立即更新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í)際上會觸發(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> ,會執(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 方法會把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ù)變化最終會把flushSchedulerQueue傳入到nextTick中執(zhí)行flushSchedulerQueue函數(shù)會遍歷執(zhí)行watcher.run()方法,watcher.run()方法最終會完成視圖更新,接下來我們看關(guān)鍵的nextTick方法到底是啥

2.2 nextTick

nextTick方法會被傳進(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會優(yōu)先使用microTask, 其次是macroTask 。

也就是說nextTick中的任務(wù),實(shí)際上會異步執(zhí)行,nextTick(callback)類似于
Promise.resolve().then(callback),或者setTimeout(callback, 0)。

也就是說vue的視圖更新 nextTick(flushSchedulerQueue)等同于setTimeout(flushSchedulerQueue, 0),會異步執(zhí)行flushSchedulerQueue函數(shù),所以我們在this.msg = hello 并不會立即更新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ù)會在渲染的異步任務(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為了保證性能,會把dom修改添加到異步任務(wù),所有同步代碼執(zhí)行完成后再統(tǒng)一修改dom,一次事件循環(huán)中的多次數(shù)據(jù)修改只會觸發(fā)一次watcher.run()。也就是通過nextTick,nextTick會優(yōu)先使用microTask創(chuàng)建異步任務(wù)。

vue項(xiàng)目中如果需要獲取修改后的dom信息,需要通過nextTick在dom更新任務(wù)之后創(chuàng)建一個(gè)異步任務(wù)。如官網(wǎng)所說,nextTick會在下次 DOM 更新循環(huán)結(jié)束之后執(zhí)行延遲回調(diào)。

參考文章

Vue nextTick 機(jī)制

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • vue.js初學(xué)入門教程(1)

    vue.js初學(xué)入門教程(1)

    這篇文章主要為大家詳細(xì)介紹了vue.js初學(xué)入門教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • 基于vue-upload-component封裝一個(gè)圖片上傳組件的示例

    基于vue-upload-component封裝一個(gè)圖片上傳組件的示例

    這篇文章主要介紹了基于vue-upload-component封裝一個(gè)圖片上傳組件的示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-10-10
  • Vue項(xiàng)目啟動(dòng)報(bào)錯(cuò)解決方法大全

    Vue項(xiàng)目啟動(dòng)報(bào)錯(cuò)解決方法大全

    這篇文章主要給大家介紹了關(guān)于Vue項(xiàng)目啟動(dòng)報(bào)錯(cuò)解決方法的相關(guān)資料,文中通過圖文將解決的過程介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用vue具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-07-07
  • vue3如何解決各場景l(fā)oading過度(避免白屏尷尬!)

    vue3如何解決各場景l(fā)oading過度(避免白屏尷尬!)

    在開發(fā)的過程中點(diǎn)擊提交按鈕,或者是一些其它場景總會遇到loading加載,下面這篇文章主要給大家介紹了關(guān)于vue3如何解決各場景l(fā)oading過度的相關(guān)資料,避免白屏尷尬,需要的朋友可以參考下
    2023-03-03
  • vite+vue3中require?is?not?defined問題及解決

    vite+vue3中require?is?not?defined問題及解決

    這篇文章主要介紹了vite+vue3中require?is?not?defined問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-05-05
  • vue結(jié)合vue-electron創(chuàng)建應(yīng)用程序小結(jié)

    vue結(jié)合vue-electron創(chuàng)建應(yīng)用程序小結(jié)

    這篇文章主要介紹了vue結(jié)合vue-electron創(chuàng)建應(yīng)用程序,本文給大家介紹了安裝electron有兩種方式,兩種方式創(chuàng)建的項(xiàng)目結(jié)構(gòu)大不相同,需要的朋友可以參考下
    2024-03-03
  • WebPack配置vue多頁面的技巧

    WebPack配置vue多頁面的技巧

    這篇文章主要介紹了WebPack配置vue多頁面的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2018-05-05
  • Vue之插槽的內(nèi)容渲染問題及解決過程

    Vue之插槽的內(nèi)容渲染問題及解決過程

    本文將探討這些常見問題的原因,并提供相應(yīng)的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-03-03
  • Vue實(shí)現(xiàn)骨架屏的示例代碼

    Vue實(shí)現(xiàn)骨架屏的示例代碼

    骨架屏就是在頁面數(shù)據(jù)尚未加載前先給用戶展示出頁面的大致結(jié)構(gòu)。本文將利用Vue實(shí)現(xiàn)簡單的骨架屏,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-03-03
  • vue組件內(nèi)部引入外部js文件的方法

    vue組件內(nèi)部引入外部js文件的方法

    這篇文章主要介紹了vue組件內(nèi)部引入外部js文件的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-01-01

最新評論

城市| 山丹县| 临沭县| 巫山县| 淮滨县| 赞皇县| 石狮市| 靖宇县| 克什克腾旗| 苏尼特左旗| 石城县| 蚌埠市| 九龙坡区| 瑞金市| 平利县| 炎陵县| 庆阳市| 余姚市| 北票市| 南靖县| 榕江县| 江孜县| 错那县| 乡城县| 丰宁| 吉林省| 迁安市| 开阳县| 龙川县| 应城市| 巴马| 竹北市| 清涧县| 汶川县| 闽侯县| 彰化市| 深州市| 宁南县| 晋江市| 屯昌县| 黄大仙区|