vue組件的更新:異步、批量


vue組件的更新:異步、批量

Vue組件的更新:

  • 異步
  • 批量

主要利用瀏覽器事件輪詢的微任務機制來實現組件的異步批量更新。

當偵測到數據變化,vue會開啟一個隊列,將相關聯的Watcher實例存入隊列,將回調函數存入callbacks隊列。異步執行回調函數,遍歷watcher隊列進行渲染。

  • 異步: Vue更新DOM時是異步執行的。
    • 一旦偵測到數據變化,key對應的Dep實例就會通知更新:dep.notify()。notify(): 遍歷subs中所有的watcher,調用update()方法
    • watcher.update():update方法會調用queueWatcher(this)將wathcer進行入隊操作
      • queueWatcher(watcher):通過watcher.id, 來判斷has數組中是否有,如果沒有,將watcher推入queue隊列中。如果已經push過了,就不在入隊了。將該watcher入隊的時候,還會調用nextTick(flushSchedulerQueue)方法。
      • nextTick(flushSchedulerQueue):nextTick():將watcher需要更新的回調函數push入callbacks數組,callbacks數組存放的是一系列需要執行的回調函數,callbacks:[()=>{cb.call(ctx)}]。
  • 批量:在同一個事件循環下,vue將更新放入微任務隊列中,一次性更新該組件
    • 當同步代碼執行完,瀏覽器會在更新頁面之前,先清空微任務隊列microtask queue,微任務隊列中有一個callbacks,里面存放的是vue更新組件的一些列更新代碼。同時微任務隊列中還會存放一些vue組件中用戶自定義的一些異步任務。
      • 如果同一個watcher被多次觸發(每次該key對應的數據被重新賦值,就會觸發一次該watcher.update()),只會被推入隊列中一次。去重可避免不必要的計算和DOM操作。
      • 瀏覽器在下一個事件輪詢前,清空微任務隊列后,就會刷新一次頁面。在同一個事件輪詢的周期內,所有待更新watcher都會批量執行完,在下次刷新頁面中一次性全部更新掉。
  • 異步策略:Vue內部對異步隊列嘗試使用Promise.reslove().then()、MutationObserver、setImmediate,如果執行環境不支持,則會采用 setTimeout(fn, 0) 代替。先嘗試使用微任務方式,不行再用宏任務方式。

異步批量更新流程圖:
data中的數據發生改變,key對應的dep就會觸發notify(),notify方法:遍歷相關的watcher,調用update方法。
image

批量異步更新源碼

當data中的某個數據更新時:

① 觸發Object.defineProperty()中的setter訪問器屬性

core/oberver/index.js:

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()
    }

② 調用dep.notify(): 遍歷所有相關watcher,調用wathcer.update()

core/oberver/dep.js:

// 通知所有相關的watcher進行更新
  notify () {
    // stabilize the subscriber list first
    // 重新定義一個數組 subs ,該數組不會影響this.subs里面的元素。
    // slice(start,end): 選中從start開始,end(不包含)結束的元素,再返回一個新數組
    // this.subs.slice() = this.subs.slice(0) = this.subs.slice(0, this.subs.length)
    // this.subs中存放的是一個個的watcher實例
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // subs aren't sorted in scheduler if not running async
      // we need to sort them now to make sure they fire in correct
      // order
      subs.sort((a, b) => a.id - b.id)
    }
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }

③ 執行watcher.update(): 判斷是立即更新還是異步更新。若為異步更新,調用queueWatcher(this),將watcher入隊,放到后面一起更新。

core/oberver/watcher.js:

update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) {
      //立即執行渲染
      this.run()
    } else {
      // watcher入隊操作,后面一起執行渲染
      queueWatcher(this)
    }
}

④ 執行queueWatcher(this): watcher進行去重等操作,push到queue隊列中,再調用nextTick(flushSchedulerQueue)執行異步隊列,傳入回調函數 flushSchedulerQueue。

core/oberver/scheduler.js:

function queueWatcher (watcher: Watcher) {
  // has 標識,是一個數組,判斷該watcher是否已在,避免在一個隊列中添加相同的 Watcher
  const id = watcher.id
  if (has[id] == null) {
    has[id] = true
    // flushing 標識,處理 Watcher 渲染時,可能產生的新 Watcher。
    if (!flushing) {
      // 將當前 Watcher 添加到異步隊列
      queue.push(watcher)
    } else {
      // 產生新的watcher就添加到排序的位置
      let i = queue.length - 1
      while (i > index && queue[i].id > watcher.id) {
        i--
      }
      queue.splice(i + 1, 0, watcher)
    }
    // queue the flush
    // waiting 標識,讓所有的 Watcher 都在一個 tick 內進行更新。
    if (!waiting) {
      waiting = true
  
      if (process.env.NODE_ENV !== 'production' && !config.async) {
        flushSchedulerQueue()
        return
      }
      // 執行異步隊列,並傳入回調
      nextTick(flushSchedulerQueue)
    }
  }
}

⑤ 執行nextTick(cb):將傳入的flushSchedulerQueue函數處理后()=>{if(cb){cb.call(ctx)}...}傳入callbacks數組中,調用timerFunc函數異步執行任務。

core/util/next-tick.js:

function nextTick (cb?: Function, ctx?: Object) {
  let _resolve
  // 此處的callbacks就是隊列(回調數組),將傳入的 flushSchedulerQueue 方法處理后添加到回調數組
  // cb:有可能是是用戶在組件內部調用$nextTick(cb)傳入的cb
  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
    })
  }
}

⑥ timerFunc():根據瀏覽器兼容性,選用不同的異步方式執行flushCallbacks。由於宏任務耗費的時間是大於微任務的,所以優先選擇微任務的方式,都不行時再使用宏任務的方式。

core/util/next-tick.js:

let timerFunc
  
// 支持Promise則使用Promise異步的方式執行flushCallbacks
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) ||
  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 {
  // 實在不行再使用setTimeout的異步方式
  timerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

⑦ flushCallbacks: 異步執行callbacks隊列中的所有回調函數

core/util.next-tick.js

// 循環callbacks隊列,執行里面所有函數flushSchedulerQueue,並清空隊列
function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

⑧ flushSchedulerQueue(): 遍歷watcher隊列,執行watcher.run()函數

watcher.run():真正的渲染。

function flushSchedulerQueue() {
  currentFlushTimestamp = getNow();
  flushing = true;
  let watcher, id;
  
  // 排序,先渲染父節點,再渲染子節點
  // 這樣可以避免不必要的子節點渲染,如:父節點中 v-if 為 false 的子節點,就不用渲染了
  queue.sort((a, b) => a.id - b.id);
  
  // do not cache length because more watchers might be pushed
  // as we run existing watchers
  // 遍歷所有 Watcher 進行批量更新。
  for (index = 0; index < queue.length; index++) {
    watcher = queue[index];
    if (watcher.before) {
      watcher.before();
    }
    id = watcher.id;
    has[id] = null;
    // 真正的更新函數
    watcher.run();
    // in dev build, check and stop circular updates.
    if (process.env.NODE_ENV !== "production" && has[id] != null) {
      circular[id] = (circular[id] || 0) + 1;
      if (circular[id] > MAX_UPDATE_COUNT) {
        warn(
          "You may have an infinite update loop " +
            (watcher.user
              ? `in watcher with expression "${watcher.expression}"`
              : `in a component render function.`),
          watcher.vm
        );
        break;
      }
    }
  }
  
  // keep copies of post queues before resetting state
  const activatedQueue = activatedChildren.slice();
  const updatedQueue = queue.slice();
  
  resetSchedulerState();
  
  // call component updated and activated hooks
  callActivatedHooks(activatedQueue);
  callUpdatedHooks(updatedQueue);
  
  // devtool hook
  /* istanbul ignore if */
  if (devtools && config.devtools) {
    devtools.emit("flush");
  }
}

⑨ watcher.run(): watcher真正的更新函數是run,而非update

core/observer/watcher.js:

  run () {
    if (this.active) {
      const value = this.get()
      if (
        value !== this.value ||
        // Deep watchers and watchers on Object/Arrays should fire even
        // when the value is the same, because the value may
        // have mutated.
        isObject(value) ||
        this.deep
      ) {
        // set new value
        const oldValue = this.value
        this.value = value
        // 用戶自定義的watcher(在組件內使用watcher監聽屬性的變化)
        if (this.user) {
          const info = `callback for watcher "${this.expression}"`
          invokeWithErrorHandling(this.cb, this.vm, [value, oldValue], this.vm, info)
        } else {
          // vue組件本身的更新
          // this.cb: 是new Vue()在$mount()掛載時創建new Watcher()傳入的回調函數: updateComponent
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }

⑩ updateComponent(): watcher.run() 經過一系列的執行,最終執行的this.cb.call(this.vm, value, oldValue)這里的this.cb就是new Watcher傳入的回調函數updateComponent, updateComponent中執行render(),讓組件重新渲染, 再執行_update(vnode) ,再執行 patch()更新界面。

⑪ _update():根據是否有vnode分別執行不同的patch。

Vue.nextTick(callback)

Vue.nextTick(callback):在callback回調中,vue組件是異步更新完成后的狀態。這里可以獲取更新后的DOM元素

Vue在更新DOM時是異步執行的,所以在修改data之后,並不能立刻獲取到修改后的Dom元素。如果想在同步修改代碼后,獲取修改后的DOM元素,可以再Vue.nextTick(callback)中獲取。

為什么Vue.$nextTick 能獲取更新后的DOM

因為Vue.$nextTick 就是調用的nextTick 方法,在異步隊列中執行回調函數

Vue.prototype.$nextTick = function (fn: Function) {
  return nextTick(fn, this);
};

Vue組件異步更新demo

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue的批量、異步更新</title>
  <script src="../../dist/vue.js"></script>
</head>
<body>
<div id="demo">
  <h3>vue的批量、異步更新</h3>
  <p id="p1">{{foo}}</p>
</div>
<script>
  new Vue({
    el: '#demo',
    data: {
      foo: 'ready~~'
    },
    beforeCreate() {
      console.log('★★★beforeCreate,還沒有進行數據響應式,也沒有wathcer實例。已經進行了$parent/$root/$children、事件初始化、$slots $nextTicket $createElement render。')
    },
    created() {
      console.log('★★★created,已經完成inject、state、provide初始化。響應式數據已經完成。沒有wathcer實例。')
    },
    mounted() {
      console.log('★★★我已經進入mounted鈎子函數,已經生成了Watcher實例了')
      
      // vue組件更新,是利用瀏覽器的事件輪詢的微任務來操作的。★★★ 異步、批量
      // 1. 異步: 同步代碼中進行數據重新賦值,view視圖層中的代碼是不會立即更新的。數據重新賦值,就會觸發watcher的update方法,該方法會調用queueWatcher(this)方法,該方法調用nextTick(flushSchedulerQueue),nextTick():方法就是push入callbacks數組的方法,將需要更新的watcher實例push進微任務隊列的一個callbacks數組中,callbacks數組存放的是一系列需要執行的回調函數,callbacks:[()=>{cb.call(ctx)}]。當然,如果watcher實例已經push進去了,下次更新,如果push的是同一個wathcer實例,是不會進這個callbacks數組的。同時,這個同步代碼是不會立即改變view層的代碼的,即這個組件是不會立即更新的。如果沒有別的額外操作,是要等瀏覽器的6ms一次的刷新,清空瀏覽的microtask queue后,才會一起在view層中展現。
      // 2. 批量:同步改變響應式對象的值,wathcer的update函數,會將wathcer實例進行入隊操作queueWatcher(this),一直等到所有同步代碼執行完,並且清空微任務隊列之后,才會批量的將所有變動都展示在頁面上。
      this.foo = Math.random()
      // foo進行重新賦值,defineReactive方法中,使用Object.defineProperty()的訪問器屬性的setter來設置值,同時通知改key對應的Dep實例調用notify()方法
      // notify方法: 1.Dep對象的subs數組中存放的是與之關聯的Watcher實例:① vue組件初始化生成的Watcher實例, ② 用戶自定義的watcher監聽的Watcher實例。 2. 遍歷subs中watcher,依次調用watcher.update()方法
      // watcher的update()方法: 將該wathcer實例,進行入隊操作: queueWatcher(this),該方法調用nextTick(flushSchedulerQueue),將該key的Dep實例關聯的Watcher實例推入到callbacks數組中,等待瀏覽器清空微任務隊列。此時callbacks中push進一個cb
      console.log('1:' + this.foo);
      this.foo = Math.random()
      // this.foo第二次同步代碼賦值,watcher實例不會推入callbacks數組。即,進入queueWatcher(this)后,不會執行nextTick(flushSchedulerQueue)方法。此時callbacks中還是只有一個cb。nextTick():方法就是push入callbacks數組的方法
      console.log('2:' + this.foo);
      this.foo = Math.random()
      // this.foo第三次同步代碼賦值,watcher實例不會推入callbacks數組。即,進入queueWatcher(this)后,不會執行nextTick(flushSchedulerQueue)方法。此時callbacks中還是只有一個cb。
      console.log('3:' + this.foo);

      // 此時同步代碼還沒執行完,至少,還沒進入清空microtask queue,所以,view層的數據仍然是上一次的數據,即初始化的值。
      console.log('p1.innerHTML:' + p1.innerHTML)

      // Promise.resolve().then(() => {
      //     // 這里才是最新的值
      //     console.log('p1.innerHTML:' + p1.innerHTML)
      // })

      this.$nextTick(() => {
        // 這里才是最新的值
        // 使用this.$nextTick(cb),將()=>{cb.call(ctx)}push進callbacks,所以callbacks中,目前有2個[()=>{ flushSchedulerQueue.call(ctx)}, ()=>{ 此處的回調函數}]
        // 第一個cb是將view視圖層的數據更新
        // 第二個cb是這里的console打印dom的innerHTML
        console.log('p1.innerHTML:' + p1.innerHTML)
      })
    }
  })

</script>
</body>
</html>

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue的批量、異步更新</title>
  <script src="../../dist/vue.js"></script>
</head>
<body>
<div id="demo">
  <h3>vue的批量、異步更新</h3>
  <p id="p1">{{foo}}</p>
</div>
<script>
  new Vue({
    el: '#demo',
    data: {
      foo: 'ready~~'
    },
    beforeCreate() {
      console.log('★★★beforeCreate,還沒有進行數據響應式,也沒有wathcer實例。已經進行了$parent/$root/$children、事件初始化、$slots $nextTicket $createElement render。')
    },
    created() {
      console.log('★★★created,已經完成inject、state、provide初始化。響應式數據已經完成。沒有wathcer實例。')
    },
    mounted() {
      console.log('★★★我已經進入mounted鈎子函數,已經生成了Watcher實例了')
      
      // vue組件更新,是利用瀏覽器的事件輪詢的微任務來操作的。★★★ 異步、批量
      // 1. 異步: 同步代碼中進行數據重新賦值,view視圖層中的代碼是不會立即更新的。數據重新賦值,就會觸發watcher的update方法,該方法會調用queueWatcher(this)方法,該方法調用nextTick(flushSchedulerQueue),nextTick():方法就是push入callbacks數組的方法,將需要更新的watcher實例push進微任務隊列的一個callbacks數組中,callbacks數組存放的是一系列需要執行的回調函數,callbacks:[()=>{cb.call(ctx)}]。當然,如果watcher實例已經push進去了,下次更新,如果push的是同一個wathcer實例,是不會進這個callbacks數組的。同時,這個同步代碼是不會立即改變view層的代碼的,即這個組件是不會立即更新的。如果沒有別的額外操作,是要等瀏覽器的6ms一次的刷新,清空瀏覽的microtask queue后,才會一起在view層中展現。
      // 2. 批量:同步改變響應式對象的值,wathcer的update函數,會將wathcer實例進行入隊操作queueWatcher(this),一直等到所有同步代碼執行完,並且清空微任務隊列之后,才會批量的將所有變動都展示在頁面上。

      // callbacks = []
      // microtaskQueue = [callbacks]
      this.$nextTick(() => {
        // 這里才是最新的值
        // 使用this.$nextTick(cb),將()=>{cb.call(ctx)}push進callbacks,所以callbacks中,目前有2個[()=>{ flushSchedulerQueue.call(ctx)}, ()=>{ 此處的回調函數}]
        // 第一個cb是將view視圖層的數據更新
        // 第二個cb是這里的console打印dom的innerHTML
        console.log('$nextTick: p1.innerHTML:' + p1.innerHTML)
      })
      // callbacks: [()=>{$nextTickCB()}]
      // microtaskQueue = [callbacks]

      this.foo = Math.random()
      console.log('4:' + this.foo);
      // callbacks: [()=>{$nextTickCB()}, flushSchedulerQueue]
      // microtaskQueue = [callbacks]
      this.foo = Math.random()
      console.log('5:' + this.foo);

      console.log('p1.innerHTML:' + p1.innerHTML)

      // 4, 5, p1.innerHTML:reader~~,  $nextTick: p1.innerHTML:reader~~

    }
  })


</script>
</body>
</html>

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>vue的批量、異步更新</title>
  <script src="../../dist/vue.js"></script>
</head>
<body>
<div id="demo">
  <h3>vue的批量、異步更新</h3>
  <p id="p1">{{foo}}</p>
</div>
<script>
  new Vue({
    el: '#demo',
    data: {
      foo: 'ready~~'
    },
    beforeCreate() {
      console.log('★★★beforeCreate,還沒有進行數據響應式,也沒有wathcer實例。已經進行了$parent/$root/$children、事件初始化、$slots $nextTicket $createElement render。')
    },
    created() {
      console.log('★★★created,已經完成inject、state、provide初始化。響應式數據已經完成。沒有wathcer實例。')
    },
    mounted() {
      console.log('★★★我已經進入mounted鈎子函數,已經生成了Watcher實例了')

      // vue組件更新,是利用瀏覽器的事件輪詢的微任務來操作的。★★★ 異步、批量
      // 1. 異步: 同步代碼中進行數據重新賦值,view視圖層中的代碼是不會立即更新的。數據重新賦值,就會觸發watcher的update方法,該方法會調用queueWatcher(this)方法,該方法調用nextTick(flushSchedulerQueue),nextTick():方法就是push入callbacks數組的方法,將需要更新的watcher實例push進微任務隊列的一個callbacks數組中,callbacks數組存放的是一系列需要執行的回調函數,callbacks:[()=>{cb.call(ctx)}]。當然,如果watcher實例已經push進去了,下次更新,如果push的是同一個wathcer實例,是不會進這個callbacks數組的。同時,這個同步代碼是不會立即改變view層的代碼的,即這個組件是不會立即更新的。如果沒有別的額外操作,是要等瀏覽器的6ms一次的刷新,清空瀏覽的microtask queue后,才會一起在view層中展現。
      // 2. 批量:同步改變響應式對象的值,wathcer的update函數,會將wathcer實例進行入隊操作queueWatcher(this),一直等到所有同步代碼執行完,並且清空微任務隊列之后,才會批量的將所有變動都展示在頁面上。

      // callbacks:[]
      // microtaskQueue : []
      Promise.resolve().then(()=>{
        console.log('Promise: p1.innerHTML:' + p1.innerHTML)
      })
      // callbacks: []
      // microtaskQueue = [p.then()]

      this.foo = Math.random()
      console.log('8:' + this.foo);
      // callbacks: [flushSchedulerQueue]
      // microtaskQueue = [p.then(),callbacks]
      this.foo = Math.random()
      console.log('9:' + this.foo);
      console.log('p1.innerHTML:' + p1.innerHTML)

      // 8, 9, p1.innerHTML:ready~~, Promise: p1.innerHTML:ready~~

    }
  })

</script>
</body>
</html>

<template>
  <p id="test">{{foo}}</p>
</template>
<script>
  
export default{
  data(){
    return {
      foo: 'foo'
    }
  },
  mounted() {
    // callbacks:[]
    // cb: ()=>{console.log('nextTick:test.innerHTML:' + test.innerHTML);}
    let test  = document.querySelector('#test');
    
// callbacks:[cb]
    this.$nextTick(() => {
      // nextTick回調是在觸發更新之前就放入callbacks隊列,
      // 壓根沒有觸發watcher.update以及以后的一系列操作,所以也就沒有執行到最后的watcher.run()實行渲染
      // 所以此處DOM並未更新
      console.log('nextTick:test.innerHTML:' + test.innerHTML);
    })
    
// callbacks: [cb, flushSchedulerQueue]
    this.foo = 'foo1';
    // vue在更新DOM時是異步進行的,所以此處DOM並未更新
    console.log('1.test.innerHTML:' + test.innerHTML); 
    
// callbacks: [cb, flushSchedulerQueue]
    this.foo = 'foo2';
    // 此處DOM並未更新,且先於異步回調函數前執行
    console.log('2.test.innerHTML:' + test.innerHTML); 
  }
}
</script>
cb: ()=>{console.log('nextTick:test.innerHTML:' + test.innerHTML);}
callbacks:[]
callbacks:[cb]
callbacks: [cb, flushSchedulerQueue]
callbacks: [cb, flushSchedulerQueue]
執行結果:
1.test.innerHTML:foo
2.test.innerHTML:foo
nextTick:test.innerHTML:foo
<template>
  <p id="test">{{foo}}</p>
</template>
<script>
  
export default{
  data(){
    return {
      foo: 'foo'
    }
  },
  mounted() {
    
// callbacks: []
// microtaskQueue: []
// macrotaskQueue: []
    
    
    let test  = document.querySelector('#test');
    this.$nextTick(() => {
      // nextTick回調是在觸發更新之前就放入callbacks隊列,
      // 壓根沒有觸發watcher.update以及以后的一系列操作,所以也就沒有執行到最后的watcher.run()實行渲染
      // 所以此處DOM並未更新
      console.log('nextTick:test.innerHTML:' + test.innerHTML); 
    })
  
// callbacks: [cb]    
// microtaskQueue: [callbacks]
// macrotaskQueue: []
    
    
    this.foo = 'foo1';
    
// callbacks: [cb, flushSchedulerQueue]    
// microtaskQueue: [callbacks]
// macrotaskQueue: []    
    
    // vue在更新DOM時是異步進行的,所以此處DOM並未更新
    console.log('1.test.innerHTML:' + test.innerHTML); 
    this.foo = 'foo2';
    
// callbacks: [cb, flushSchedulerQueue]    
// microtaskQueue: [callbacks]
// macrotaskQueue: []   
    
    
    // 此處DOM並未更新,且先於異步回調函數前執行
    console.log('2.test.innerHTML:' + test.innerHTML); 
  
    Promise.resolve().then(() => {
      console.log('Promise:test.innerHTML:' + test.innerHTML); 
    });
    
// callbacks: [cb, flushSchedulerQueue]    
// microtaskQueue: [callbacks, Promise.resolve().then]
// macrotaskQueue: []  
    
    setTimeout(() => {
        console.log('setTimeout:test.innerHTML:' + test.innerHTML);
    });
    
// callbacks: [cb, flushSchedulerQueue]    
// microtaskQueue: [callbacks, Promise.resolve().then]
// macrotaskQueue: [setTimeout]      
    
  }
}
</script>
執行結果:
1.test.innerHTML:foo
2.test.innerHTML:foo
nextTick:test.innerHTML:foo
Promise:test.innerHTML:foo2
setTimeout:test.innerHTML:foo2
<template>
  <p id="test">{{foo}}</p>
</template>
<script>
  
export default{
  data(){
    return {
      foo: 'foo'
    }
  },
  mounted() {
    
    
// callbacks: []
// microtaskQueue: []
// macrotaskQueue: []    
    
    let test  = document.querySelector('#test');
    // Promise 和 setTimeout 依舊是等到DOM更新后再執行
    
    Promise.resolve().then(() => {
      console.log('Promise:test.innerHTML:' + test.innerHTML); 
    });
    
// callbacks: []
// microtaskQueue: [Promise.resolve().then]
// macrotaskQueue: []
    
    setTimeout(() => {
        console.log('setTimeout:test.innerHTML:' + test.innerHTML);
    });
        
// callbacks: []
// microtaskQueue: [Promise.resolve().then]
// macrotaskQueue: [setTimeout]
    
    
    this.$nextTick(() => {
      // nextTick回調是在觸發更新之前就放入callbacks隊列,
      // 壓根沒有觸發watcher.update以及以后的一系列操作,所以也就沒有執行到最后的watcher.run()實行渲染
      // 所以此處DOM並未更新
      console.log('nextTick:test.innerHTML:' + test.innerHTML); 
    })
           
// callbacks: [cb]
// microtaskQueue: [Promise.resolve().then, callbacks]
// macrotaskQueue: [setTimeout]
    
       
    this.foo = 'foo1';
               
// callbacks: [cb, flushSchedulerQueue]
// microtaskQueue: [Promise.resolve().then, callbacks]
// macrotaskQueue: [setTimeout]
    

    // vue在更新DOM時是異步進行的,所以此處DOM並未更新
    console.log('1.test.innerHTML:' + test.innerHTML); 
    this.foo = 'foo2';
                   
// callbacks: [cb, flushSchedulerQueue]
// microtaskQueue: [Promise.resolve().then, callbacks]
// macrotaskQueue: [setTimeout]
    
    // 此處DOM並未更新,且先於異步回調函數前執行
    console.log('2.test.innerHTML:' + test.innerHTML); 
  }
}
</script>
執行結果:
1.test.innerHTML:foo
2.test.innerHTML:foo
Promise:test.innerHTML:foo
nextTick:test.innerHTML:foo2
setTimeout:test.innerHTML:foo2

只有在microtaskQueue隊列中執行到callbacks隊列時,頁面的dom元素的值才會改變。

在microtaskQueue隊列執行到callbacks隊列之前所以的代碼獲取的dom元素都是舊值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM