Vue批量更新dom的實現步驟

場景介紹

在一個SFC(single file component,單文件組件)中,我們經常會寫這樣的邏輯:

<template>
  <div>
    <span>{{ a }}</span>
    <span>{{ b }}</span>
  </div>  
</template>
<script type="javascript">
export default {
  data() {
    return {
      a: 0,
      b: 0
    }
  },
  created() {
    // some logic code
    this.a = 1
    this.b = 2
  }
}
</script>

你可能知道,在完成this.a和this.b的賦值操作後,Vue會將this.a和this.b相應的dom更新函數放到一個微任務中。等待主線程的同步任務執行完畢後,該微任務會出隊並執行。我們看看Vue的官方文檔”深入響應式原理-聲明響應式property”一節中,是怎麼進行描述的:

可能你還沒有註意到,Vue 在更新 DOM 時是異步執行的。隻要偵聽到數據變化,Vue 將開啟一個隊列,並緩沖在同一事件循環中發生的所有數據變更。

那麼,Vue是怎麼實現這一能力的呢?為瞭回答這個問題,我們需要深入Vue源碼的核心部分——響應式原理。

深入響應式

我們首先看一看在我們對this.a和this.b進行賦值操作以後,發生瞭什麼。如果使用Vue CLI進行開發,在main.js文件中,會有一個new Vue()的實例化操作。由於Vue的源碼是使用flow寫的,無形中增加瞭理解成本。為瞭方便,我們直接看npm vue包中dist文件夾中的vue.js源碼。搜索‘function Vue’,找到瞭以下源碼:

function Vue (options) {
  if (!(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword');
  }
  this._init(options);
}

非常簡單的源碼,源碼真的沒有我們想象中那麼難!帶著這樣的意外驚喜,我們繼續找到_init函數,看看這個函數做瞭什麼:

Vue.prototype._init = function (options) {
  var vm = this;
  // a uid
  vm._uid = uid$3++;

  var startTag, endTag;
  /* istanbul ignore if */
  if (config.performance && mark) {
    startTag = "vue-perf-start:" + (vm._uid);
    endTag = "vue-perf-end:" + (vm._uid);
    mark(startTag);
  }

  // a flag to avoid this being observed
  vm._isVue = true;
  // merge options
  if (options && options._isComponent) {
    // optimize internal component instantiation
    // since dynamic options merging is pretty slow, and none of the
    // internal component options needs special treatment.
    initInternalComponent(vm, options);
  } else {
    vm.$options = mergeOptions(
      resolveConstructorOptions(vm.constructor),
      options || {},
      vm
    );
  }
  /* istanbul ignore else */
  {
    initProxy(vm);
  }
  // expose real self
  vm._self = vm;
  initLifecycle(vm);
  initEvents(vm);
  initRender(vm);
  callHook(vm, 'beforeCreate');
  initInjections(vm); // resolve injections before data/props
  initState(vm);
  initProvide(vm); // resolve provide after data/props
  callHook(vm, 'created');

  /* istanbul ignore if */
  if (config.performance && mark) {
    vm._name = formatComponentName(vm, false);
    mark(endTag);
    measure(("vue " + (vm._name) + " init"), startTag, endTag);
  }

  if (vm.$options.el) {
    vm.$mount(vm.$options.el);
  }
}

我們先不管上面的一堆判斷,直接拉到下面的主邏輯。可以看到,_init函數先後執行瞭initLifeCycle、initEvents、initRender、callHook、initInjections、initState、initProvide以及第二次callHook函數。從函數的命名來看,我們可以知道具體的意思。大體來說,這段代碼分為以下兩個部分

  1. 在完成初始化生命周期、事件鉤子以及渲染函數後,進入beforeCreate生命周期(執行beforeCreate函數)
  2. 在完成初始化註入值、狀態以及提供值之後,進入created生命周期(執行created函數)

其中,我們關心的數據響應式原理部分在initState函數中,我們看看這個函數做瞭什麼:

function initState (vm) {
  vm._watchers = [];
  var opts = vm.$options;
  if (opts.props) { initProps(vm, opts.props); }
  if (opts.methods) { initMethods(vm, opts.methods); }
  if (opts.data) {
    initData(vm);
  } else {
    observe(vm._data = {}, true /* asRootData */);
  }
  if (opts.computed) { initComputed(vm, opts.computed); }
  if (opts.watch && opts.watch !== nativeWatch) {
    initWatch(vm, opts.watch);
  }
}

這裡我們看到瞭在書寫SFC文件時常常見到的幾個配置項:props、methods、data、computed和watch。我們將註意力集中到opts.data部分,這一部分執行瞭initData函數:

function initData (vm) {
  var data = vm.$options.data;
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {};
  if (!isPlainObject(data)) {
    data = {};
    warn(
      'data functions should return an object:\n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    );
  }
  // proxy data on instance
  var keys = Object.keys(data);
  var props = vm.$options.props;
  var methods = vm.$options.methods;
  var i = keys.length;
  while (i--) {
    var key = keys[i];
    {
      if (methods && hasOwn(methods, key)) {
        warn(
          ("Method \"" + key + "\" has already been defined as a data property."),
          vm
        );
      }
    }
    if (props && hasOwn(props, key)) {
      warn(
        "The data property \"" + key + "\" is already declared as a prop. " +
        "Use prop default value instead.",
        vm
      );
    } else if (!isReserved(key)) {
      proxy(vm, "_data", key);
    }
  }
  // observe data
  observe(data, true /* asRootData */);
}

我們在寫data配置項時,會將其定義為函數,因此這裡執行瞭getData函數:

function getData (data, vm) {
  // #7573 disable dep collection when invoking data getters
  pushTarget();
  try {
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, "data()");
    return {}
  } finally {
    popTarget();
  }
}

getData函數做的事情非常簡單,就是在組件實例上下文中執行data函數。註意,在執行data函數前後,分別執行瞭pushTarget函數和popTarget函數,這兩個函數我們後面再講。

執行getData函數後,我們回到initData函數,後面有一個循環的錯誤判斷,暫時不用管。於是我們來到瞭observe函數:

function observe (value, asRootData) {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  var ob;
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__;
  } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value);
  }
  if (asRootData && ob) {
    ob.vmCount++;
  }
  return ob
}

observe函數為data對象創建瞭一個觀察者(ob),也就是實例化Observer,實例化Observer具體做瞭什麼呢?我們繼續看源碼:

var Observer = function Observer (value) {
  this.value = value;
  this.dep = new Dep();
  this.vmCount = 0;
  def(value, '__ob__', this);
  if (Array.isArray(value)) {
    if (hasProto) {
      protoAugment(value, arrayMethods);
    } else {
      copyAugment(value, arrayMethods, arrayKeys);
    }
    this.observeArray(value);
  } else {
    this.walk(value);
  }
}

正常情況下,因為我們定義的data函數返回的都是一個對象,所以這裡我們先不管對數組的處理。那麼就是繼續執行walk函數:

Observer.prototype.walk = function walk (obj) {
  var keys = Object.keys(obj);
  for (var i = 0; i < keys.length; i++) {
    defineReactive$$1(obj, keys[i]);
  }
}

對於data函數返回的對象,即組件實例的data對象中的每個可枚舉屬性,執行defineReactive$$1函數:

function defineReactive$$1 (
  obj,
  key,
  val,
  customSetter,
  shallow
) {
  var dep = new Dep();

  var property = Object.getOwnPropertyDescriptor(obj, key);
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  var getter = property && property.get;
  var setter = property && property.set;
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key];
  }

  var childOb = !shallow && observe(val);
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      var 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) {
      var 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 (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();
    }
  });
}

在defineReactive$$1函數中,首先實例化一個依賴收集器。然後使用Object.defineProperty重新定義對象屬性的getter(即上面的get函數)和setter(即上面的set函數)。

觸發getter

getter和setter某種意義上可以理解為回調函數,當讀取對象某個屬性的值時,會觸發get函數(即getter);當設置對象某個屬性的值時,會觸發set函數(即setter)。我們回到最開始的例子:

<template>
  <div>
    <span>{{ a }}</span>
    <span>{{ b }}</span>
  </div>  
</template>
<script type="javascript">
export default {
  data() {
    return {
      a: 0,
      b: 0
    }
  },
  created() {
    // some logic code
    this.a = 1
    this.b = 2
  }
}
</script>

這裡有設置this對象的屬性a和屬性b的值,因此會觸發setter。我們把上面set函數代碼單獨拿出來:

function reactiveSetter (newVal) {
  var 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 (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();
}

setter先執行瞭getter:

function reactiveGetter () {
  var value = getter ? getter.call(obj) : val;
  if (Dep.target) {
    dep.depend();
    if (childOb) {
      childOb.dep.depend();
      if (Array.isArray(value)) {
        dependArray(value);
      }
    }
  }
  return value
}

getter先檢測Dep.target是否存在。在前面執行getData函數的時候,Dep.target的初始值為null,它在什麼時候被賦值瞭呢?我們前面講getData函數的時候,有看到一個pushTarget函數和popTarget函數,這兩個函數的源碼如下:

Dep.target = null;
var targetStack = [];

function pushTarget (target) {
  targetStack.push(target);
  Dep.target = target;
}

function popTarget () {
  targetStack.pop();
  Dep.target = targetStack[targetStack.length - 1];
}

想要正常執行getter,就需要先執行pushTarget函數。我們找找pushTarget函數在哪裡執行的。在vue.js中搜索pushTarget,我們找到瞭5個地方,除去定義的地方,執行的地方有4個。
第一個執行pushTarget函數的地方。這是一個處理錯誤的函數,正常邏輯不會觸發:

function handleError (err, vm, info) {
  // Deactivate deps tracking while processing error handler to avoid possible infinite rendering.
  // See: https://github.com/vuejs/vuex/issues/1505
  pushTarget();
  try {
    if (vm) {
      var cur = vm;
      while ((cur = cur.$parent)) {
        var hooks = cur.$options.errorCaptured;
        if (hooks) {
          for (var i = 0; i < hooks.length; i++) {
            try {
              var capture = hooks[i].call(cur, err, vm, info) === false;
              if (capture) { return }
            } catch (e) {
              globalHandleError(e, cur, 'errorCaptured hook');
            }
          }
        }
      }
    }
    globalHandleError(err, vm, info);
  } finally {
    popTarget();
  }
}

第二個執行pushTarget的地方。這是調用對應的鉤子函數。在執行到對應的鉤子函數時會觸發。不過,我們現在的操作介於beforeCreate鉤子和created鉤子之間,還沒有觸發:

function callHook (vm, hook) {
  // #7573 disable dep collection when invoking lifecycle hooks
  pushTarget();
  var handlers = vm.$options[hook];
  var info = hook + " hook";
  if (handlers) {
    for (var i = 0, j = handlers.length; i < j; i++) {
      invokeWithErrorHandling(handlers[i], vm, null, vm, info);
    }
  }
  if (vm._hasHookEvent) {
    vm.$emit('hook:' + hook);
  }
  popTarget();
}

第三個執行pushTarget的地方。這是實例化watcher時執行的函數。檢查前面的代碼,我們似乎也沒有看到new Watcher的操作:

Watcher.prototype.get = function get () {
  pushTarget(this);
  var value;
  var vm = this.vm;
  try {
    value = this.getter.call(vm, vm);
  } catch (e) {
    if (this.user) {
      handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\""));
    } else {
      throw e
    }
  } finally {
    // "touch" every property so they are all tracked as
    // dependencies for deep watching
    if (this.deep) {
      traverse(value);
    }
    popTarget();
    this.cleanupDeps();
  }
  return value
}

第四個執行pushTarget的地方,這就是前面的getData函數。但是getData函數的執行位於defineReactive$$1函數之前。在執行完getData函數以後,Dep.target已經被重置為null瞭。

function getData (data, vm) {
  // #7573 disable dep collection when invoking data getters
  pushTarget();
  try {
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, "data()");
    return {}
  } finally {
    popTarget();
  }
}

看起來,直接觸發setter並不能讓getter中的邏輯正常執行。並且,我們還發現,由於setter中也有Dep.target的判斷,所以如果我們找不到Dep.target的來源,setter的邏輯也無法繼續往下走。

尋找Dep.target

那麼,到底Dep.target的值是從哪裡來的呢?不用著急,我們回到_init函數的操作繼續往下看:

Vue.prototype._init = function (options) {
  var vm = this;
  // a uid
  vm._uid = uid$3++;

  var startTag, endTag;
  /* istanbul ignore if */
  if (config.performance && mark) {
    startTag = "vue-perf-start:" + (vm._uid);
    endTag = "vue-perf-end:" + (vm._uid);
    mark(startTag);
  }

  // a flag to avoid this being observed
  vm._isVue = true;
  // merge options
  if (options && options._isComponent) {
    // optimize internal component instantiation
    // since dynamic options merging is pretty slow, and none of the
    // internal component options needs special treatment.
    initInternalComponent(vm, options);
  } else {
    vm.$options = mergeOptions(
      resolveConstructorOptions(vm.constructor),
      options || {},
      vm
    );
  }
  /* istanbul ignore else */
  {
    initProxy(vm);
  }
  // expose real self
  vm._self = vm;
  initLifecycle(vm);
  initEvents(vm);
  initRender(vm);
  callHook(vm, 'beforeCreate');
  initInjections(vm); // resolve injections before data/props
  initState(vm);
  initProvide(vm); // resolve provide after data/props
  callHook(vm, 'created');

  /* istanbul ignore if */
  if (config.performance && mark) {
    vm._name = formatComponentName(vm, false);
    mark(endTag);
    measure(("vue " + (vm._name) + " init"), startTag, endTag);
  }

  if (vm.$options.el) {
    vm.$mount(vm.$options.el);
  }
}

我們發現,在_init函數的最後,執行瞭vm.$mount函數,這個函數做瞭什麼呢?

Vue.prototype.$mount = function (
  el,
  hydrating
) {
  el = el && inBrowser ? query(el) : undefined;
  return mountComponent(this, el, hydrating)
}

我們繼續進入mountComponent函數看看:

function mountComponent (
  vm,
  el,
  hydrating
) {
  vm.$el = el;
  if (!vm.$options.render) {
    vm.$options.render = createEmptyVNode;
    {
      /* istanbul ignore if */
      if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
        vm.$options.el || el) {
        warn(
          'You are using the runtime-only build of Vue where the template ' +
          'compiler is not available. Either pre-compile the templates into ' +
          'render functions, or use the compiler-included build.',
          vm
        );
      } else {
        warn(
          'Failed to mount component: template or render function not defined.',
          vm
        );
      }
    }
  }
  callHook(vm, 'beforeMount');

  var updateComponent;
  /* istanbul ignore if */
  if (config.performance && mark) {
    updateComponent = function () {
      var name = vm._name;
      var id = vm._uid;
      var startTag = "vue-perf-start:" + id;
      var endTag = "vue-perf-end:" + id;

      mark(startTag);
      var vnode = vm._render();
      mark(endTag);
      measure(("vue " + name + " render"), startTag, endTag);

      mark(startTag);
      vm._update(vnode, hydrating);
      mark(endTag);
      measure(("vue " + name + " patch"), startTag, endTag);
    };
  } else {
    updateComponent = function () {
      vm._update(vm._render(), hydrating);
    };
  }

  // we set this to vm._watcher inside the watcher's constructor
  // since the watcher's initial patch may call $forceUpdate (e.g. inside child
  // component's mounted hook), which relies on vm._watcher being already defined
  new Watcher(vm, updateComponent, noop, {
    before: function before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate');
      }
    }
  }, true /* isRenderWatcher */);
  hydrating = false;

  // manually mounted instance, call mounted on self
  // mounted is called for render-created child components in its inserted hook
  if (vm.$vnode == null) {
    vm._isMounted = true;
    callHook(vm, 'mounted');
  }
  return vm
}

我們驚喜地發現,這裡有一個new Watcher的操作!真是山重水復疑無路,柳暗花明又一村!這裡實例化的watcher是一個用來更新dom的watcher。他會依次讀取SFC文件中的template部分中的所有值。這也就意味著會觸發對應的getter。
由於new Watcher會執行watcher.get函數,該函數執行pushTarget函數,於是Dep.target被賦值。getter內部的邏輯順利執行。

getter

至此,我們終於到瞭Vue的響應式原理的核心。我們再次回到getter,看一看有瞭Dep.target以後,getter做瞭什麼:

function reactiveGetter () {
  var value = getter ? getter.call(obj) : val;
  if (Dep.target) {
    dep.depend();
    if (childOb) {
      childOb.dep.depend();
      if (Array.isArray(value)) {
        dependArray(value);
      }
    }
  }
  return value
}

同樣地,我們先不關註提高代碼健壯性的細節處理,直接看主線。可以看到,當Dep.target存在時,執行瞭dep.depend函數。這個函數做瞭什麼呢?我們看看代碼:

Dep.prototype.depend = function depend () {
  if (Dep.target) {
    Dep.target.addDep(this);
  }
}

做的事情也非常簡單。就是執行瞭Dep.target.addDep函數。但是Dep.target其實是一個watcher,所以我們要回到Watcher的代碼:

Watcher.prototype.addDep = function addDep (dep) {
  var id = dep.id;
  if (!this.newDepIds.has(id)) {
    this.newDepIds.add(id);
    this.newDeps.push(dep);
    if (!this.depIds.has(id)) {
      dep.addSub(this);
    }
  }
}

同樣地,我們先忽略一些次要的邏輯處理,把註意力集中到dep.addSub函數上:

Dep.prototype.addSub = function addSub (sub) {
  this.subs.push(sub);
}

也是非常簡單的邏輯,把watcher作為一個訂閱者推入數組中緩存。至此,getter的整個邏輯走完。此後執行popTarget函數,Dep.target被重置為null

setter

我們再次回到業務代碼:

<template>
  <div>
    <span>{{ a }}</span>
    <span>{{ b }}</span>
  </div>  
</template>
<script type="javascript">
export default {
 data() {
    return {
      a: 0,
      b: 0
    }
  },
  created() {
    // some logic code
    this.a = 1
    this.b = 2
  }
}
</script>

在created生命周期中,我們觸發瞭兩次setter,setter執行的邏輯如下:

function reactiveSetter (newVal) {
  var 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 (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();
}

這裡,我們隻需要關註setter最後執行的函數:dep.notify()。我們看看這個函數做瞭什麼:

Dep.prototype.notify = function notify () {
  // stabilize the subscriber list first
  var subs = this.subs.slice();
  if (!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(function (a, b) { return a.id - b.id; });
  }
  for (var i = 0, l = subs.length; i < l; i++) {
    subs[i].update();
  }
}

This.subs的每一項元素均為一個watcher。在上面getter章節中,我們隻收集到瞭一個watcher。因為觸發瞭兩次setter,所以subs[0].update(),即watcher.update()函數會執行兩次。我們看看這個函數做瞭什麼:

Watcher.prototype.update = function update () {
  /* istanbul ignore else */
  if (this.lazy) {
    this.dirty = true;
  } else if (this.sync) {
    this.run();
  } else {
    queueWatcher(this);
  }
}

按照慣例,我們直接跳入queueWatcher函數:

function queueWatcher (watcher) {
  var 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.
      var 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 (!config.async) {
        flushSchedulerQueue();
        return
      }
      nextTick(flushSchedulerQueue);
    }
  }
}

由於id相同,所以watcher的回調函數隻會被推入到queue一次。這裡我們再次看到瞭一個熟悉的面孔:nextTick。

function nextTick (cb, ctx) {
  var _resolve;
  callbacks.push(function () {
    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(function (resolve) {
      _resolve = resolve;
    })
  }
}

nextTick函數將回調函數再次包裹一層後,執行timerFunc()

var 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)) {
  var p = Promise.resolve();
  timerFunc = function () {
    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)
  var counter = 1;
  var observer = new MutationObserver(flushCallbacks);
  var textNode = document.createTextNode(String(counter));
  observer.observe(textNode, {
    characterData: true
  });
  timerFunc = function () {
    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 = function () {
    setImmediate(flushCallbacks);
  };
} else {
  // Fallback to setTimeout.
  timerFunc = function () {
    setTimeout(flushCallbacks, 0);
  };
}

timerFunc函數是微任務的平穩降級。他將根據所在環境的支持程度,依次調用Promise、MutationObserver、setImmediate和setTimeout。並在對應的微任務或者模擬微任務隊列中執行回調函數。

function flushSchedulerQueue () {
  currentFlushTimestamp = getNow();
  flushing = true;
  var 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(function (a, b) { return 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();
    // in dev build, check and stop circular updates.
    if (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
  var activatedQueue = activatedChildren.slice();
  var 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.prototype.run = function run () {
  if (this.active) {
    var 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
      var oldValue = this.value;
      this.value = value;
      if (this.user) {
        try {
          this.cb.call(this.vm, value, oldValue);
        } catch (e) {
          handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\""));
        }
      } else {
        this.cb.call(this.vm, value, oldValue);
      }
    }
  }
}

執行this.cb函數,即watcher的回調函數。至此,所有的邏輯走完。

總結

我們再次回到業務場景:

<template>
  <div>
    <span>{{ a }}</span>
    <span>{{ b }}</span>
  </div>  
</template>
<script type="javascript">
export default {
  data() {
    return {
      a: 0,
      b: 0
    }
  },
  created() {
    // some logic code
    this.a = 1
    this.b = 2
  }
}
</script>

雖然我們觸發瞭兩次setter,但是對應的渲染函數在微任務中卻隻執行瞭一次。也就是說,在dep.notify函數發出通知以後,Vue將對應的watcher進行瞭去重、排隊操作並最終執行回調。

可以看出,兩次賦值操作實際上觸發的是同一個渲染函數,這個渲染函數更新瞭多個dom。這就是所謂的批量更新dom。

到此這篇關於Vue批量更新dom的實現步驟的文章就介紹到這瞭,更多相關Vue批量更新dom 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: