溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Vue如何批量更新dom

發(fā)布時間:2021-07-06 13:53:19 來源:億速云 閱讀:210 作者:小新 欄目:開發(fā)技術

這篇文章將為大家詳細講解有關Vue如何批量更新dom,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

場景介紹

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

<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更新函數(shù)放到一個微任務中。等待主線程的同步任務執(zhí)行完畢后,該微任務會出隊并執(zhí)行。我們看看Vue的官方文檔"深入響應式原理-聲明響應式property"一節(jié)中,是怎么進行描述的:

可能你還沒有注意到,Vue 在更新 DOM 時是異步執(zhí)行的。只要偵聽到數(shù)據(jù)變化,Vue 將開啟一個隊列,并緩沖在同一事件循環(huán)中發(fā)生的所有數(shù)據(jù)變更。

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

深入響應式

我們首先看一看在我們對this.a和this.b進行賦值操作以后,發(fā)生了什么。如果使用Vue CLI進行開發(fā),在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);
}

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

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函數(shù)先后執(zhí)行了initLifeCycle、initEvents、initRender、callHook、initInjections、initState、initProvide以及第二次callHook函數(shù)。從函數(shù)的命名來看,我們可以知道具體的意思。大體來說,這段代碼分為以下兩個部分

  1. 在完成初始化生命周期、事件鉤子以及渲染函數(shù)后,進入beforeCreate生命周期(執(zhí)行beforeCreate函數(shù))

  2. 在完成初始化注入值、狀態(tài)以及提供值之后,進入created生命周期(執(zhí)行created函數(shù))

其中,我們關心的數(shù)據(jù)響應式原理部分在initState函數(shù)中,我們看看這個函數(shù)做了什么:

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部分,這一部分執(zhí)行了initData函數(shù):

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配置項時,會將其定義為函數(shù),因此這里執(zhí)行了getData函數(shù):

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函數(shù)做的事情非常簡單,就是在組件實例上下文中執(zhí)行data函數(shù)。注意,在執(zhí)行data函數(shù)前后,分別執(zhí)行了pushTarget函數(shù)和popTarget函數(shù),這兩個函數(shù)我們后面再講。

執(zhí)行getData函數(shù)后,我們回到initData函數(shù),后面有一個循環(huán)的錯誤判斷,暫時不用管。于是我們來到了observe函數(shù):

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函數(shù)為data對象創(chuàng)建了一個觀察者(ob),也就是實例化Observer,實例化Observer具體做了什么呢?我們繼續(xù)看源碼:

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函數(shù)返回的都是一個對象,所以這里我們先不管對數(shù)組的處理。那么就是繼續(xù)執(zhí)行walk函數(shù):

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函數(shù)返回的對象,即組件實例的data對象中的每個可枚舉屬性,執(zhí)行defineReactive$$1函數(shù):

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函數(shù)中,首先實例化一個依賴收集器。然后使用Object.defineProperty重新定義對象屬性的getter(即上面的get函數(shù))和setter(即上面的set函數(shù))。

觸發(fā)getter

getter和setter某種意義上可以理解為回調(diào)函數(shù),當讀取對象某個屬性的值時,會觸發(fā)get函數(shù)(即getter);當設置對象某個屬性的值時,會觸發(fā)set函數(shù)(即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的值,因此會觸發(fā)setter。我們把上面set函數(shù)代碼單獨拿出來:

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先執(zhí)行了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是否存在。在前面執(zhí)行getData函數(shù)的時候,Dep.target的初始值為null,它在什么時候被賦值了呢?我們前面講getData函數(shù)的時候,有看到一個pushTarget函數(shù)和popTarget函數(shù),這兩個函數(shù)的源碼如下:

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

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

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

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

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

第二個執(zhí)行pushTarget的地方。這是調(diào)用對應的鉤子函數(shù)。在執(zhí)行到對應的鉤子函數(shù)時會觸發(fā)。不過,我們現(xiàn)在的操作介于beforeCreate鉤子和created鉤子之間,還沒有觸發(fā):

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

第三個執(zhí)行pushTarget的地方。這是實例化watcher時執(zhí)行的函數(shù)。檢查前面的代碼,我們似乎也沒有看到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
}

第四個執(zhí)行pushTarget的地方,這就是前面的getData函數(shù)。但是getData函數(shù)的執(zhí)行位于defineReactive$$1函數(shù)之前。在執(zhí)行完getData函數(shù)以后,Dep.target已經(jīng)被重置為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();
  }
}

看起來,直接觸發(fā)setter并不能讓getter中的邏輯正常執(zhí)行。并且,我們還發(fā)現(xiàn),由于setter中也有Dep.target的判斷,所以如果我們找不到Dep.target的來源,setter的邏輯也無法繼續(xù)往下走。

尋找Dep.target

那么,到底Dep.target的值是從哪里來的呢?不用著急,我們回到_init函數(shù)的操作繼續(xù)往下看:

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

我們發(fā)現(xiàn),在_init函數(shù)的最后,執(zhí)行了vm.$mount函數(shù),這個函數(shù)做了什么呢?

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

我們繼續(xù)進入mountComponent函數(shù)看看:

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
}

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

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
}

同樣地,我們先不關注提高代碼健壯性的細節(jié)處理,直接看主線??梢钥吹剑擠ep.target存在時,執(zhí)行了dep.depend函數(shù)。這個函數(shù)做了什么呢?我們看看代碼:

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

做的事情也非常簡單。就是執(zhí)行了Dep.target.addDep函數(shù)。但是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函數(shù)上:

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

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

setter

我們再次回到業(yè)務代碼:

<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生命周期中,我們觸發(fā)了兩次setter,setter執(zhí)行的邏輯如下:

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最后執(zhí)行的函數(shù):dep.notify()。我們看看這個函數(shù)做了什么:

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章節(jié)中,我們只收集到了一個watcher。因為觸發(fā)了兩次setter,所以subs[0].update(),即watcher.update()函數(shù)會執(zhí)行兩次。我們看看這個函數(shù)做了什么:

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

按照慣例,我們直接跳入queueWatcher函數(shù):

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的回調(diào)函數(shù)只會被推入到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函數(shù)將回調(diào)函數(shù)再次包裹一層后,執(zhí)行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函數(shù)是微任務的平穩(wěn)降級。他將根據(jù)所在環(huán)境的支持程度,依次調(diào)用Promise、MutationObserver、setImmediate和setTimeout。并在對應的微任務或者模擬微任務隊列中執(zhí)行回調(diào)函數(shù)。

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');
  }
}

回調(diào)函數(shù)的核心邏輯是執(zhí)行watcher.run函數(shù):

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

執(zhí)行this.cb函數(shù),即watcher的回調(diào)函數(shù)。至此,所有的邏輯走完。

總結

我們再次回到業(yè)務場景:

<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>

雖然我們觸發(fā)了兩次setter,但是對應的渲染函數(shù)在微任務中卻只執(zhí)行了一次。也就是說,在dep.notify函數(shù)發(fā)出通知以后,Vue將對應的watcher進行了去重、排隊操作并最終執(zhí)行回調(diào)。

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

關于“Vue如何批量更新dom”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI