Vue.js異步更新及nextTick

文章首發於:github.com/USTB-musion…javascript

寫在前面

前段時間在寫項目時對nextTick的使用有一些疑惑。在查閱各類資料以後,在這裏總結一下Vue.js異步更新的策略以及nextTick的用途和原理。若有總結錯誤的地方,歡迎指出!html

本文將從如下3點進行總結:java

  1. 爲何Vue.js要異步更新視圖?
  2. JavaScript異步運行的機制是怎樣的?
  3. 什麼狀況下要使用nextTick?

先看一個例子

<template>
  <div>
    <div ref="message">{{message}}</div>
    <button @click="handleClick">點擊</button>
  </div>
</template>
複製代碼
export default {
    data () {
        return {
            message: 'begin'
        };
    },
    methods () {
        handleClick () {
            this.message = 'end';
            console.log(this.$refs.message.innerText); //打印「begin」
        }
    }
}
複製代碼

打印出來的結果是「begin」,咱們在點擊事件裏明明將message賦值爲「end」,而獲取真實DOM節點的innerHTML卻沒有獲得預期中的「begin」,爲何?ios

再看一個例子

<template>
  <div>
    <div>{{number}}</div>
    <div @click="handleClick">click</div>
  </div>
</template>
複製代碼
export default {
    data () {
        return {
            number: 0
        };
    },
    methods: {
        handleClick () {
            for(let i = 0; i < 10000; i++) {
                this.number++;
            }
        }
    }
}
複製代碼

在點擊click事件以後,number會被遍歷增長10000次。在Vue.js響應式系統中,能夠看一下個人前一篇文章Vue.js的響應式系統原理。咱們知道Vue.js會經歷「setter->Dep->Watcher->patch->視圖」這幾個流程。。git

根據以往的理解,每次number被+1的時候,都會觸發number的setter按照上邊的流程最後來修改真實的DOM,而後DOM被更新了10000次,想一想都刺激!看一下官網的描述:Vue 異步執行 DOM 更新。只要觀察到數據變化,Vue 將開啓一個隊列,並緩衝在同一事件循環中發生的全部數據改變。若是同一個 watcher 被屢次觸發,只會被推入到隊列中一次。這種在緩衝時去除重複數據對於避免沒必要要的計算和 DOM 操做上很是重要顯然github

JavaScript的運行機制

爲了方便理解Vue.js異步更新策略和nextTick,先介紹如下JS的運行機制,參考阮一峯老師的JavaScript 運行機制詳解:再談Event Loop。摘取的關鍵部分以下:JS是單線程的,意思就是同一時間只能作一件事情。它是基於事件輪詢的,具體能夠分爲如下幾個步驟:數組

(1)全部同步任務都在主線程上執行,造成一個執行棧(execution context stack)。app

(2)主線程以外,還存在一個"任務隊列"(task queue)。只要異步任務有了運行結果,就在"任務隊列"之中放置一個事件。異步

(3)一旦"執行棧"中的全部同步任務執行完畢,系統就會讀取"任務隊列",看看裏面有哪些事件。那些對應的異步任務,因而結束等待狀態,進入執行棧,開始執行。async

(4)主線程不斷重複上面的第三步。

上圖就是主線程和任務隊列的示意圖。只要主線程空了,就會去讀取"任務隊列",這就是JavaScript的運行機制。這個過程會不斷重複。主線程的執行過程是一個tick。全部的異步結果經過「任務隊列」來被調度。任務隊列中主要有兩大類,「macrotask」和「microtask」,這兩類task會進入任務隊列。常見的 macrotask 有 setTimeout、MessageChannel、postMessage、setImmediate;常見的 microtask 有 MutationObsever 和 Promise.then。

事件輪詢

Vue.js在修改數據的時候,不會立馬修改數據,而是要等同一事件輪詢的數據都更新完以後,再統一進行視圖更新。 知乎上的例子:

//改變數據
vm.message = 'changed'

//想要當即使用更新後的DOM。這樣不行,由於設置message後DOM尚未更新
console.log(vm.$el.textContent) // 並不會獲得'changed'

//這樣能夠,nextTick裏面的代碼會在DOM更新後執行
Vue.nextTick(function(){
    console.log(vm.$el.textContent) //能夠獲得'changed'
})
複製代碼

圖解:

模擬nextTick

nextTick在官網當中的定義:

在下次 DOM 更新循環結束以後執行延遲迴調。在修改數據以後當即使用這個方法,獲取更新後的 DOM。

如下用setTimeout來模擬nextTick,先定義一個callbacks來存儲nextTick,在下一個tick處理回調函數以前,全部的cb都會存儲到這個callbacks數組當中。pending是一個標記位,表明等待的狀態。接着setTimeout 會在 task 中建立一個事件 flushCallbacks ,flushCallbacks 則會在執行時將 callbacks 中的全部 cb 依次執行。

// 存儲nextTick
let callbacks = [];
let pending = false;

function nextTick (cb) {
    callbacks.push(cb);

    if (!pending) {
        // 表明等待狀態的標誌位
        pending = true;
        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]();
    }
}
複製代碼

真實的代碼比這兒複雜的多,在Vue.js源碼當中,nextTick定義在一個單獨的文件中來維護,在src/core/util/next-tick.js中:

/* @flow */
/* globals MessageChannel */

import { noop } from 'shared/util'
import { handleError } from './error'
import { isIOS, isNative } from './env'

const callbacks = []
let pending = false

function flushCallbacks () {
  pending = false
  const copies = callbacks.slice(0)
  callbacks.length = 0
  for (let i = 0; i < copies.length; i++) {
    copies[i]()
  }
}

// Here we have async deferring wrappers using both microtasks and (macro) tasks.
// In < 2.4 we used microtasks everywhere, but there are some scenarios where
// microtasks have too high a priority and fire in between supposedly
// sequential events (e.g. #4521, #6690) or even between bubbling of the same
// event (#6566). However, using (macro) tasks everywhere also has subtle problems
// when state is changed right before repaint (e.g. #6813, out-in transitions).
// Here we use microtask by default, but expose a way to force (macro) task when
// needed (e.g. in event handlers attached by v-on).
let microTimerFunc
let macroTimerFunc
let useMacroTask = false

// Determine (macro) task defer implementation.
// Technically setImmediate should be the ideal choice, but it's only available
// in IE. The only polyfill that consistently queues the callback after all DOM
// events triggered in the same loop is by using MessageChannel.
/* istanbul ignore if */
if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
  macroTimerFunc = () => {
    setImmediate(flushCallbacks)
  }
} else if (typeof MessageChannel !== 'undefined' && (
  isNative(MessageChannel) ||
  // PhantomJS
  MessageChannel.toString() === '[object MessageChannelConstructor]'
)) {
  const channel = new MessageChannel()
  const port = channel.port2
  channel.port1.onmessage = flushCallbacks
  macroTimerFunc = () => {
    port.postMessage(1)
  }
} else {
  /* istanbul ignore next */
  macroTimerFunc = () => {
    setTimeout(flushCallbacks, 0)
  }
}

// Determine microtask defer implementation.
/* istanbul ignore next, $flow-disable-line */
if (typeof Promise !== 'undefined' && isNative(Promise)) {
  const p = Promise.resolve()
  microTimerFunc = () => {
    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)
  }
} else {
  // fallback to macro
  microTimerFunc = macroTimerFunc
}

/** * Wrap a function so that if any code inside triggers state change, * the changes are queued using a (macro) task instead of a microtask. */
export function withMacroTask (fn: Function): Function {
  return fn._withTask || (fn._withTask = function () {
    useMacroTask = true
    const res = fn.apply(null, arguments)
    useMacroTask = false
    return res
  })
}

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
    if (useMacroTask) {
      macroTimerFunc()
    } else {
      microTimerFunc()
    }
  }
  // $flow-disable-line
  if (!cb && typeof Promise !== 'undefined') {
    return new Promise(resolve => {
      _resolve = resolve
    })
  }
}

複製代碼

加上註釋以後:

/** * Defer a task to execute it asynchronously. */
 /* 延遲一個任務使其異步執行,在下一個tick時執行,一個當即執行函數,返回一個function 這個函數的做用是在task或者microtask中推入一個timerFunc,在當前調用棧執行完之後以此執行直到執行到timerFunc 目的是延遲到當前調用棧執行完之後執行 */
export const nextTick = (function () {
  /*存放異步執行的回調*/
  const callbacks = []
  /*一個標記位,若是已經有timerFunc被推送到任務隊列中去則不須要重複推送*/
  let pending = false
  /*一個函數指針,指向函數將被推送到任務隊列中,等到主線程任務執行完時,任務隊列中的timerFunc被調用*/
  let timerFunc

  /*下一個tick時的回調*/
  function nextTickHandler () {
    /*一個標記位,標記等待狀態(即函數已經被推入任務隊列或者主線程,已經在等待當前棧執行完畢去執行),這樣就不須要在push多個回調到callbacks時將timerFunc屢次推入任務隊列或者主線程*/
    pending = false
    /*執行全部callback*/
    const copies = callbacks.slice(0)
    callbacks.length = 0
    for (let i = 0; i < copies.length; i++) {
      copies[i]()
    }
  }

  // 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 if */

  /* 這裏解釋一下,一共有Promise、MutationObserver以及setTimeout三種嘗試獲得timerFunc的方法 優先使用Promise,在Promise不存在的狀況下使用MutationObserver,這兩個方法都會在microtask中執行,會比setTimeout更早執行,因此優先使用。 若是上述兩種方法都不支持的環境則會使用setTimeout,在task尾部推入這個函數,等待調用執行。 參考:https://www.zhihu.com/question/55364497 */
  if (typeof Promise !== 'undefined' && isNative(Promise)) {
    /*使用Promise*/
    var p = Promise.resolve()
    var logError = err => { console.error(err) }
    timerFunc = () => {
      p.then(nextTickHandler).catch(logError)
      // 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)
    }
  } else if (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 IE11, iOS7, Android 4.4
    /*新建一個textNode的DOM對象,用MutationObserver綁定該DOM並指定回調函數,在DOM變化的時候則會觸發回調,該回調會進入主線程(比任務隊列優先執行),即textNode.data = String(counter)時便會觸發回調*/
    var counter = 1
    var observer = new MutationObserver(nextTickHandler)
    var textNode = document.createTextNode(String(counter))
    observer.observe(textNode, {
      characterData: true
    })
    timerFunc = () => {
      counter = (counter + 1) % 2
      textNode.data = String(counter)
    }
  } else {
    // fallback to setTimeout
    /* istanbul ignore next */
    /*使用setTimeout將回調推入任務隊列尾部*/
    timerFunc = () => {
      setTimeout(nextTickHandler, 0)
    }
  }

  /* 推送到隊列中下一個tick時執行 cb 回調函數 ctx 上下文 */
  return function queueNextTick (cb?: Function, ctx?: Object) {
    let _resolve
    /*cb存到callbacks中*/
    callbacks.push(() => {
      if (cb) {
        try {
          cb.call(ctx)
        } catch (e) {
          handleError(e, ctx, 'nextTick')
        }
      } else if (_resolve) {
        _resolve(ctx)
      }
    })
    if (!pending) {
      pending = true
      timerFunc()
    }
    if (!cb && typeof Promise !== 'undefined') {
      return new Promise((resolve, reject) => {
        _resolve = resolve
      })
    }
  }
})()
複製代碼

關鍵在於timeFunc(),該函數起到延遲執行的做用。 從上面的介紹,能夠得知timeFunc()一共有三種實現方式。

  • Promise
  • MutationObserver
  • setTimeout

用途

nextTick的用途

應用場景:須要在視圖更新以後,基於新的視圖進行操做。

看一個例子: 點擊show按鈕使得原來v-show:false的input輸入框顯示,並獲取焦點:

<div id="app">
  <input ref="input" v-show="inputShow">
  <button @click="show">show</button>  
 </div>
複製代碼
new Vue({
  el: "#app",
  data() {
   return {
     inputShow: false
   }
  },
  methods: {
    show() {
      this.inputShow = true
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    }
  }
})
複製代碼
相關文章
相關標籤/搜索