從源碼解析vue的響應式原理-響應式的總體流程

前言

vue官方對響應式原理的解釋:深刻響應式原理javascript

上一節講了VUE中依賴收集和依賴觸發的原理,然鵝對響應式的總體流程咱們仍是有不少疑問:html

  • VUE是什麼時候進行依賴收集的?
  • 依賴觸發了之後又是怎麼進行頁面響應式變化的?
  • watcher對象到底起到了什麼做用?

爲了回答以上的幾個問題,咱們不得不梳理一波VUE響應式的總體流程vue


從實例初始化階段開始提及

vue源碼的 instance/init.js 中是初始化的入口,其中初始化中除了初始化的幾個步驟之外,在最後有這樣一段 代碼:java

if (vm.$options.el) {
	vm.$mount(vm.$options.el)
}
複製代碼

在初始化結束後,調用mount()方法將組件掛載掛載至給定的元素vm.options.el中。node

關於$mount的定義在兩處能夠看到:platforms/web/runtime/index.js、platforms/web/entry-runtime-with-compiler.jsreact

其中runtime/index.js的代碼以下:web

Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component {
  el = el && inBrowser ? query(el) : undefined
  // 劃重點!!!
  return mountComponent(this, el, hydrating)
}
複製代碼

runtime/index.js是運行時vue的入口,其中定義的mount()方法是運行時vue的mount功能,其中主要調用了mountComponent()函數完成掛載。 entry-runtime-with-compiler.js是完整的vue的入口,在運行時vue的$mount基礎上加入了編譯模版的能力。express

編譯模版,爲掛載提供渲染函數

entry-runtime-with-compiler.js中定義了mount(),在運行時mount()的基礎上添加了模版編譯。代碼以下:ide

Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component {
  el = el && query(el)

  //檢查掛載點是否是<body>元素或者<html>元素
  if (el === document.body || el === document.documentElement) {
    process.env.NODE_ENV !== 'production' && warn(
      `Do not mount Vue to <html> or <body> - mount to normal elements instead.`
    )
    return this
  }

  const options = this.$options
  // 判斷渲染函數不存在時
  if (!options.render) {
    ...//構建渲染函數
  }
  
  //調用運行時vue的$mount()函數,
  return mount.call(this, el, hydrating)
}
複製代碼

entry-runtime-with-compiler.js中的$mount()函數主要作了三件事:函數

  1. 判斷掛載點是否是元素或者元素,由於掛載點會被自身模版替代掉,所以掛載點不能爲元素或者元素;
  2. 判斷渲染函數是否存在,若是渲染函數不存在,則構建渲染函數;
  3. 調用運行時vue的mount()函數,即runtime/index.js中的mount();

建立渲染函數

上述第二步,若渲染函數不存在時,構建渲染函數,代碼以下:

let template = options.template
 	//若是template存在,則經過template獲取真正的【模版】
    if (template) {
      //template是字符串
      if (typeof template === 'string') {
        //template第一個字符是#,則將該字符串做爲id選擇器獲取對應元素做爲【模版】
        if (template.charAt(0) === '#') {
          template = idToTemplate(template)
          ... //省略
        }
        //若是template是元素節點,則將template的innerHTML做爲【模版】
      } else if (template.nodeType) {
        template = template.innerHTML
        //若template無效,則顯示提示
      } else {
        if (process.env.NODE_ENV !== 'production') {
          warn('invalid template option:' + template, this)
        }
        return this
      }
      //若template不存在,則將el元素的outerHTML做爲【模版】
    } else if (el) {
      template = getOuterHTML(el)
    }
    //此時template中是最終的【模版】,下面根據【模版】生成rander函數
    if (template) {
      ... //省略
      // 劃重點!!!
      // 使用compileToFunctions函數將【模版】template,編譯成爲渲染函數。
      const { render, staticRenderFns } = compileToFunctions(template, {
        shouldDecodeNewlines,
        shouldDecodeNewlinesForHref,
        delimiters: options.delimiters,
        comments: options.comments
      }, this)
      options.render = render
      options.staticRenderFns = staticRenderFns

      ... //省略
    }			
複製代碼

建立渲染函數階段主要作了兩件事:

  1. 獲得【模版】字符串:
    • 若是template存在,且template是字符串以#開頭,則將該字符串做爲id選擇器獲取對應元素做爲【模版】
    • 若是template是元素節點,則將template的innerHTML做爲【模版】
    • 若是tempalte是無效字符串,則顯示warning
    • 若template不存在,則將el元素的outerHTML做爲【模版】
  2. 根據【模版】字符串生成渲染函數render()
    • 生成的options.render,在掛載組件的mountComponent函數中用到

實現掛載的mountComponent()函數

上一步確保渲染函數render()存在後,就進入到了這正的掛載階段。前面講到掛載函數主要在mountComponent()中完成。

mountComponent()函數的定義在src/core/instance/lifecycle.js文件中。代碼以下:

export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean ): Component {
  vm.$el = el
  //若是render不存在
  if (!vm.$options.render) {
    //爲render賦初始值,並打印warning提示信息
    vm.$options.render = createEmptyVNode
    ... //省略
    }
  }
  //觸發beforeMount鉤子
  callHook(vm, 'beforeMount')
  // 開始掛載
  let updateComponent
  /* istanbul ignore if */
  // 定義並初始化updateComponent函數
  if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
    updateComponent = () => {
      const name = vm._name
      const id = vm._uid
      const startTag = `vue-perf-start:${id}`
      const endTag = `vue-perf-end:${id}`

      mark(startTag)
      // 調用_render函數生成vnode虛擬節點
      const vnode = vm._render()
      mark(endTag)
      measure(`vue ${name} render`, startTag, endTag)

      mark(startTag)
      // 以虛擬節點vnode做爲參數調用_update函數,生成真正的DOM
      vm._update(vnode, hydrating)
      mark(endTag)
      measure(`vue ${name} patch`, startTag, endTag)
    }
  } else {
    updateComponent = () => {
      //調用_render函數生成vnode虛擬節點;以虛擬節點vnode做爲參數調用_update函數,生成真正的DOM
      vm._update(vm._render(), hydrating)
    }
  }
複製代碼

mountComponent主要作了三件事:

  1. 若是render不存在,爲render賦初始值,並打印warning信息
  2. 觸發beforeMount
  3. 定義並初始化updateComponent函數:
  • 調用_render函數生成vnode虛擬節點
  • 虛擬節點vnode做爲參數調用_update函數,生成真正的DOM

Watcher類

watcher類的定義在core/observer/watcher.js中,代碼以下:

export default class Watcher {
  ... //
  // 構造函數
  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    if (isRenderWatcher) {
      // 將渲染函數的觀察者存入_watcher
      vm._watcher = this
    }
    //將全部觀察者push到_watchers列表
    vm._watchers.push(this)
    // options
    if (options) {
      // 是否深度觀測
      this.deep = !!options.deep
      // 是否爲開發者定義的watcher(渲染函數觀察者、計算屬性觀察者屬於內部定義的watcher)
      this.user = !!options.user
      // 是否爲計算屬性的觀察者
      this.computed = !!options.computed
      this.sync = !!options.sync
      //在數據變化以後、觸發更新以前調用
      this.before = options.before
    } else {
      this.deep = this.user = this.computed = this.sync = false
    }
    // 定義一系列實例屬性
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.computed // for computed watchers
    this.deps = []
    this.newDeps = []
    // depIds 和 newDepIds 用書避免重複收集依賴
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // parse expression for getter
    // 兼容被觀測數據,當被觀測數據是function時,直接將其做爲getter
    // 當被觀測數據不是function時經過parsePath解析其真正的返回值
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = function () {}
        process.env.NODE_ENV !== 'production' && warn(
          `Failed watching path: "${expOrFn}" ` +
          'Watcher only accepts simple dot-delimited paths. ' +
          'For full control, use a function instead.',
          vm
        )
      }
    }
    if (this.computed) {
      this.value = undefined
      this.dep = new Dep()
    } else {
      // 除計算屬性的觀察者之外的全部觀察者調用this.get()方法
      this.value = this.get()
    }
  }

  // get方法
  get () {
    ...
  }
  // 添加依賴
  addDep (dep: Dep) {
    ...
  }
  // 移除廢棄觀察者;清空newDepIds 屬性和 newDeps 屬性的值
  cleanupDeps () {
    ...
  }
  // 當依賴變化時,觸發更新
  update () {
    ...
  }
  // 數據變化函數的入口
  run () {
    ...
  }
  // 真正進行數據變化的函數
  getAndInvoke (cb: Function) {
    ...
  }
  //
  evaluate () {
    ...
  }
  //
  depend () {
    ...
  }

  //
  teardown () {
    ...
  }
}
複製代碼

watcher構造函數

由以上代碼可見,在watcher構造函數中作了以下幾件事:

  1. 將組件的渲染函數的觀察者存入_watcher,將全部的觀察者存入_watchers中
  2. 保存before函數,在數據變化以後、觸發更新以前調用
  3. 定義一系列實例屬性
  4. 兼容被觀測數據,當被觀測數據是function時,直接將其做爲getter; 當被觀測數據不是function時經過parsePath解析其真正的返回值,被觀測數據是 'obj.name'時,經過parsePath拿到真正的obj.name的返回值
  5. 除計算屬性的觀察者之外的全部觀察者調用this.get()方法

get()中收集依賴

get中的代碼以下:

get () {
    // 將觀察者對象保存至Dep.target中(Dep.target在上一章提到過)
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      //調用getter方法,得到被觀察目標的值
      value = this.getter.call(vm, vm)
    } catch (e) {
      ...
    } finally {
      ...
    }
    return value
  }
複製代碼

get()函數中主要作了以下幾件事:

  1. 調用pushTarget()方法,將觀察者對象保存至Dep.target中,其中Dep.target在上一章提到過
  2. 調用defineReactive中的get實現依賴收集、返回正確值
  3. 上一章講過,defineReactive中調用dep.depend(),dep.depend()中調用Dep.target.addDep()進行依賴收集

addDep添加依賴

// 添加依賴
  addDep (dep: Dep) {
    const id = dep.id
    // newDepIds避免本次get中重複收集依賴
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      // 避免屢次求值中重複收集依賴,每次求值以後newDepIds會被清空,所以須要depIds來判斷。newDepIds中清空
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }
複製代碼
  • 在addDep中添加依賴,並避免對一個數據屢次求值時,其觀察者被重複收集。
  • newDepIds避免一次求值的過程當中重複收集依賴
  • depIds 屬性避免屢次求值中重複收集依賴

響應式的總體流程

根據上一章和本章的講解,總結一下響應式的總體流程: 假設有模版:

<div id="test">
  {{str}}
</div>
複製代碼
  1. 調用$mount()函數進入到掛載階段
  2. 檢查是否有render()函數,根據上述模版建立render()函數
  3. 調用了mountComponent()函數完成掛載,並在mountComponen()中定義並初始化updateComponent()
  4. 爲渲染函數添加觀察者,在觀察者中對渲染函數求值
  5. 在求值的過程當中觸發數據對象str的get,在str的get中收集str的觀察者到數據的dep中
  6. 修改str的值時,觸發str的set,在set中調用數據的dep的notify觸發響應
  7. notify中對每個觀察者調用update方法
  8. 在run中調用getAndInvoke函數,進行數據變化。 在getAndInvoke函數中調用回調函數
  9. 對於渲染函數的觀察者來講getAndInvoke就至關於執行updateComponent函數
  10. 在updateComponent函數中調用_render函數生成vnode虛擬節點,以虛擬節點vnode做爲參數調用_update函數,生成真正的DOM

至此響應式過程完成。

參考文章:揭開數據響應系統的面紗

相關文章
相關標籤/搜索