<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Vue異步更新機制和nextTick原理

          共 8705字,需瀏覽 18分鐘

           ·

          2020-07-28 16:25

          作者 | WahFung
          來源 | https ://www.cnblogs.com/chanwahfung/p/13296293.html

          前言

          最初更新是??vue核心??實現(xiàn)之一,在整體流程中預先著手觀看者更新的調(diào)度者這一角色。大部分觀察者更新都會通過它的處理,在適當時機讓更新有序的執(zhí)行。而nextTick作為替代更新的核心,也是需要學習的重點。
          本文你能學習到:
          • 初步更新的作用

          • nextTick原理

          • 初步更新流程


          js運行機制

          在理解初步更新前,需要對js運行機制進行了解,如果你已經(jīng)知道這些知識,可以選擇跳過這部分內(nèi)容。
          js執(zhí)行是單線程的,它是基于事件循環(huán)的。事件循環(huán)大致分為以下幾個步驟:
          • 所有同步任務(wù)都在主線程上執(zhí)行,形成一個執(zhí)行棧(執(zhí)行上下文堆棧)。

          • 主線程之外,還存在一個“任務(wù)隊列”(task queue)。只要初始化任務(wù)有了運行結(jié)果,就在“任務(wù)變量”之中放置一個事件。

          • 一旦“執(zhí)行棧”中的所有同步任務(wù)執(zhí)行完畢,系統(tǒng)就會重新“任務(wù)類別”,看看里面有什么事件。那些對應的初始化任務(wù),于是結(jié)束等待狀態(tài),進入執(zhí)行棧,開始執(zhí)行。

          • 主線程不斷重復上面的第三步。



          “任務(wù)類別”中的任務(wù)(任務(wù))被分為兩個類,分別是宏任務(wù)(宏任務(wù))和微任務(wù)(micro task)
          宏任務(wù):在一次新的事件循環(huán)的過程中,遇到宏任務(wù)時,宏任務(wù)將被加入任務(wù)類別,但需要等到下一次事件循環(huán)才會執(zhí)行。常見的宏任務(wù)有setTimeout,setImmediate,requestAnimationFrame
          微任務(wù):當前事件循環(huán)的任務(wù)隊列為空時,微任務(wù)隊列中的任務(wù)就會被依次執(zhí)行在執(zhí)行過程中,如果遇到微任務(wù),微任務(wù)被加入到當前事件循環(huán)的微任務(wù)隊列中。簡單來說,只要有微任務(wù)就會繼續(xù)執(zhí)行,而不是放到下一個事件循環(huán)才執(zhí)行。常見的微任務(wù)有MutationObserver,Promise.then
          總的來說,在事件循環(huán)中,微任務(wù)會先于宏任務(wù)執(zhí)行。而在微任務(wù)執(zhí)行完后會進入瀏覽器更新渲染階段,所以在更新渲染前使用微任務(wù)會比宏任務(wù)快一些。

          為什么需要初步更新

          既然異步更新是核心之一,首先要知道它的作用是什么,解決了什么問題。
          先來看一個很常見的場景:
          created(){ this.id = 10 this.list = [] this.info = {}}
          總所周知,vue??基于數(shù)據(jù)驅(qū)動視圖,數(shù)據(jù)更改會觸發(fā)setter??函數(shù),通知觀察者進行更新。如果像上面的情況,是不是代表需要更新3次,而且在實際開發(fā)中的更新可不止那么少。
          更新過程是需要經(jīng)過繁雜的操作,例如模板編譯,dom diff,不斷進行更新的性能當然很差。
          VUE??作為一個優(yōu)秀的框架,當然不會那么“直男”,來多少就照單全收。VUE??內(nèi)部實際是將觀看者加入到一個隊列數(shù)組中,最后再觸發(fā)隊列中所有觀察家的運行方法來更新。
          并且加入隊列的過程中將會對watcher進行去重操作,因為在一個組件中數(shù)據(jù)內(nèi)定義的數(shù)據(jù)都是存儲同一個“渲染watcher”,所以以上場景中數(shù)據(jù)甚至更新了3次,最終也只會執(zhí)行一次更新頁面的邏輯。
          為了達到這種效果,vue??使用異步更新,等待所有數(shù)據(jù)同步修改完成后,再去執(zhí)行更新邏輯。

          nextTick原理

          異步更新內(nèi)部是最重要的就是nextTick方法,它負責將異步任務(wù)加入隊列和執(zhí)行異步任務(wù)。VUE??也將它暴露出來提供給用戶使用。在數(shù)據(jù)修改完成后,立即獲取相關(guān)DOM還沒那么快更新,使用nextTick便可以解決這一問題。

          認識nextTick

          官方文檔對它的描述:
          在下一DOM更新循環(huán)結(jié)束之后執(zhí)行連續(xù)的替代。在修改數(shù)據(jù)之后立即使用此方法,獲取更新后的DOM。
          // 修改數(shù)據(jù)vm.msg = 'Hello'// DOM 還沒有更新vue.nextTick(function () { // DOM 更新了})
          // 作為一個 Promise 使用 (2.1.0 起新增,詳見接下來的提示)vue.nextTick() .then(function () { // DOM 更新了 })
          nextTick使用方法有一種和Promise兩種,以上是通過構(gòu)造函數(shù)調(diào)用的形式,更常見的是在實例調(diào)用this。$ nextTick。它們都是同一個方法。

          內(nèi)部實現(xiàn)

          在??vue??源碼2.5+后,nextTick的實現(xiàn)單獨有一個js文件來維護它,它的內(nèi)核并不復雜,代碼實現(xiàn)不過100行,稍微花點時間可以啃下來。
          比特位置在src / core / util /下一步?js,接下來我們來看一下它的實現(xiàn),先從入口函數(shù)開始:
          export function nextTick (cb?: Function, ctx?: Object) { let _resolve // 1 callbacks.push(() => { if (cb) { try { cb.call(ctx) } catch (e) { handleError(e, ctx, 'nextTick') } } else if (_resolve) { _resolve(ctx) } }) // 2 if (!pending) { pending = true timerFunc() } // $flow-disable-line // 3 if (!cb && typeof Promise !== 'undefined') { return new Promise(resolve => { _resolve = resolve }) }}
          • cb即預期的最大值,它被push進一個回調(diào)回調(diào),等待調(diào)用。

          • 等待的作用就是一個鎖,防止后續(xù)的nextTick重復執(zhí)行timerFunc。timerFunc內(nèi)部創(chuàng)建會一個微任務(wù)或宏任務(wù),等待所有的nextTick同步執(zhí)行完成后,再去執(zhí)行回調(diào)內(nèi)部的替代。

          • 如果沒有預先設(shè)定的,用戶可能使用的是Promise形式,返回一個Promise,_resolve被調(diào)用時進入到。


          繼續(xù)往下走看看timerFunc的實現(xiàn):
          // Here we have async deferring wrappers using microtasks.// In 2.5 we used (macro) tasks (in combination with microtasks).// However, it has subtle problems when state is changed right before repaint// (e.g. #6813, out-in transitions).// Also, using (macro) tasks in event handler would cause some weird behaviors// that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109).// So we now use microtasks everywhere, again.// A major drawback of this tradeoff is that there are some scenarios// where microtasks have too high a priority and fire in between supposedly// sequential events (e.g. #4521, #6690, which have workarounds)// or even between bubbling of the same event (#6566).let timerFunc
          // The nextTick behavior leverages the microtask queue, which can be accessed// via either native Promise.then or MutationObserver.// MutationObserver has wider support, however it is seriously bugged in// UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It// completely stops working after triggering a few times... so, if native// Promise is available, we will use it:/* istanbul ignore next, $flow-disable-line */if (typeof Promise !== 'undefined' && isNative(Promise)) {const p = Promise.resolve() timerFunc = () => { p.then(flushCallbacks) // In problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) setTimeout(noop) } isUsingMicroTask = true} else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // Phantomjs and iOS 7.x MutationObserver.toString() === '[object MutationObserverconstructor]')) { // Use MutationObserver where native Promise is not available, // e.g. Phantomjs, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) let counter = 1const 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)) { // Fallback to setImmediate. // Technically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = () => { setImmediate(flushCallbacks) }} else { // Fallback to setTimeout. timerFunc = () => { setTimeout(flushCallbacks, 0) }}
          頂層的代碼并不復雜,主要通過一些兼容的判斷來創(chuàng)建合適的timerFunc,最優(yōu)先肯定是微任務(wù),其次再到宏任務(wù)。
          優(yōu)先級為promise.then> MutationObserver> setImmediate> setTimeout。也很重要,它們能幫助我們理解設(shè)計的意義)
          我們會發(fā)現(xiàn)在某種情況下創(chuàng)建的timerFunc,最終都會執(zhí)行一個flushCallbacks的函數(shù)
          const callbacks = []let pending = false
          function flushCallbacks () { pending = falseconst copies = callbacks.slice(0) callbacks.length = 0 for (let i = 0; i < copies.length; i++) { copies[i]() }}
          flushCallbacks里做的事情是如此簡單,它負責執(zhí)行回調(diào)里的事情。
          好了,nextTick的原始碼那么那么多,現(xiàn)在已經(jīng)知道它的實現(xiàn),下面再結(jié)合轉(zhuǎn)化更新流程,讓我們對它更充分的理解吧。

          初步更新流程

          數(shù)據(jù)被改變時,觸發(fā)watcher.update
          // 源碼位置:src/core/observer/watcher.jsupdate () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true } else if (this.sync) { this.run() } else { queueWatcher(this) // this 為當前的實例 watcher }}
          調(diào)用queueWatcher,將watcher加入
          // 源碼位置:src/core/observer/scheduler.jsconst queue = []let has = {}let waiting = falselet flushing = falselet index = 0
          export function queueWatcher (watcher: Watcher) {const id = watcher.id // 1 if (has[id] == null) { has[id] = true // 2 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 // 3 if (!waiting) { waiting = true nextTick(flushSchedulerQueue) } }}
          • 每個監(jiān)視者都有他們自己的id,當沒有記錄到對應的監(jiān)視者,即第一次進入邏輯,否則是重復的監(jiān)視者,則不會進入。這一步就是實現(xiàn)監(jiān)視者去重的點。

          • 將watcher加入到體重中,等待執(zhí)行

          • 等待的作用是防止nextTick重復執(zhí)行

          flushSchedulerQueue作為替代預期nextTick初始化執(zhí)行。
          function flushSchedulerQueue () { currentFlushTimestamp = getNow() flushing = true let watcher, id
          // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort((a, b) => a.id - b.id)
          // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index] if (watcher.before) { watcher.before() } id = watcher.id has[id] = null watcher.run() }
          // keep copies of post queues before resetting stateconst activatedQueue = activatedChildren.slice() const updatedQueue = queue.slice()
          resetSchedulerState()
          // call component updated and activated hooks callActivatedHooks(activatedQueue) callUpdatedHooks(updatedQueue)}
          flushSchedulerQueue內(nèi)將剛剛加入隊列的觀察者逐個運行更新。resetSchedulerState重置狀態(tài),等待下一輪的異步更新。
          function resetSchedulerState () { index = queue.length = activatedChildren.length = 0 has = {} if (process.env.NODE_ENV !== 'production') { circular = {} } waiting = flushing = false}
          要注意此時flushSchedulerQueue仍未執(zhí)行,它只是作為一個預期的插入而已。因為用戶可能會調(diào)用nextTick方法。
          這種情況下,回調(diào)里的內(nèi)容為[“ flushSchedulerQueue”,“用戶的nextTick選擇”],當所有同步任務(wù)執(zhí)行完成,才開始執(zhí)行回調(diào)里面的一部分。
          由此可見,最先執(zhí)行的是頁面更新的邏輯,其次再到用戶的nextTick將會執(zhí)行。這也是為什么我們能在nextTick中獲取到更新后DOM的原因。

          總結(jié)

          初始更新機制使用微任務(wù)或宏任務(wù),基于事件循環(huán)運行,在??vue??中對性能起著至關(guān)重要的作用,它對重復重復的watcher進行過濾。而nextTick根據(jù)不同的環(huán)境,使用優(yōu)先級最高的初始任務(wù)。
          此類的好處是等待所有的狀態(tài)同步更新完成后,再一次性渲染頁面。用戶創(chuàng)建的nextTick運行頁面更新之后,因此能夠獲取更新后的DOM。
          本文完~
          瀏覽 43
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  白丝美女自慰网站 | 亚洲中文电影 | 一本无码免费 | 亚洲天堂人妻 | 一区二区小视频 |