Vue源碼系列-4- Vue爲什麼採用異步渲染以及原理

爲什麼採用異步渲染?


因爲如果不採用異步更新,那麼每次更新數據都會對當前組件進行重新渲染, 這樣就會可能進行大量的dom重流或者重繪,所以爲了性能考慮,減少瀏覽器在Vue每次更新數據後會出現的Dom開銷,Vue 會在本輪數據更新後,再去異步更新視圖!


src/core/observer/index.js
在 defineReactive() 這個方法中定義setter 的時候 有個 dep.notify() 方法

export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

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

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

  let childOb = !shallow && observe(val) // 遞歸觀測
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () { // 數據的取值
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
        dep.depend()  // 收集依賴 watcher
        if (childOb) {
          childOb.dep.depend()  // 收集依賴
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    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() // 觸發數據對應的依賴進行更新
    }
  })
}

接着看 notify() 這個方法
src/core/observer/dep.js

export default class Dep {
  static target: ?Watcher;
  id: number;
  subs: Array<Watcher>;

  constructor () {
    this.id = uid++
    this.subs = []
  }

  addSub (sub: Watcher) {
    this.subs.push(sub)
  }

  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }

  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  notify () { // 通知存儲的依賴更新
    // stabilize the subscriber list first
    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() // 依賴中的update方法
    }
  }
}

這裏主要做的就是 通知 watcher 進行更新操作,同時還進行了排序操作, 最後依次調用了 每個watcher 的update() 方法,

接着看這個 update () 方法

src/core/observer/watcher.js

export default class Watcher {
  /**
   * Subscriber interface.
   * Will be called when a dependency changes.
   */
  update () {
    /* istanbul ignore else */
    if (this.lazy) {
      this.dirty = true
    } else if (this.sync) { // 同步watcher
      this.run()
    } else {
      queueWatcher(this) // 
    }
  }
}

這裏有個 queueWatcher() 方法

src/core/observer/scheduler.js

/**
 * Push a watcher into the watcher queue.
 * Jobs with duplicate IDs will be skipped unless it's
 * pushed when the queue is being flushed.
 */
export function queueWatcher (watcher: Watcher) {
  const id = watcher.id // 過濾watcher  多個屬性依賴同一個watcher
  if (has[id] == null) {
    has[id] = true
    if (!flushing) {
      queue.push(watcher) // 將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
    if (!waiting) {
      waiting = true

      if (process.env.NODE_ENV !== 'production' && !config.async) {
        flushSchedulerQueue()
        return
      }
      nextTick(flushSchedulerQueue) 
    }
  }
}

在這個方法內部做了2件事

  1. 通過給每個watcher 添加個 id 屬性 ,也就是去重操作,來過濾watcher 多個屬性依賴同一個watcher
  2. queue.push(watcher) ,將watcher放到隊列中
  3. 最後調用 nextTick() 方法,來進行做異步清空 watcher 隊列的操作

可以喵一眼這個方法(flushSchedulerQueue),內部使用了 高階函數
watcher.before()
實際執行是在 run 方法中

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() // before方法
    }
    id = watcher.id
    has[id] = null
    watcher.run() // 執行watcher
    // 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) // 更新後調用的 updated

  // devtool hook
  /* istanbul ignore if */
  if (devtools && config.devtools) {
    devtools.emit('flush')
  }
}

簡單總結下原理:

  1. 調用 notify() 方法,通知watcher 進行更新操作
  2. 依次調用watcher 的 update 方法
  3. 對watcher 進行去重操作(通過id),放到隊列裏
  4. 執行完後異步清空這個隊列, nextTick(flushSchedulerQueue) 進行批量更新操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章