深度解析 Vue 響應式原理—源碼級

官網如是說

當你把一個普通的 JavaScript 對象傳入 Vue 實例做爲 data 選項,Vue 將遍歷此對象全部的 property,並使用 Object.defineProperty 把這些 property 所有轉爲 getter/setter。Object.defineProperty 是 ES5 中一個沒法 shim 的特性,這也就是 Vue 不支持 IE8 以及更低版本瀏覽器的緣由。javascript

這些 getter/setter 對用戶來講是不可見的,可是在內部它們讓 Vue 可以追蹤依賴,在 property 被訪問和修改時通知變動。這裏須要注意的是不一樣瀏覽器在控制檯打印數據對象時對 getter/setter 的格式化並不一樣,因此建議安裝 vue-devtools 來獲取對檢查數據更加友好的用戶界面。html

每一個組件實例都對應一個 watcher 實例,它會在組件渲染的過程當中把「接觸」過的數據 property 記錄爲依賴。以後當依賴項的 setter 觸發時,會通知 watcher,從而使它關聯的組件從新渲染。vue

在這裏插入圖片描述

1、理解vue中的響應式

vue中的響應式能夠理解爲:當你的狀態改變時,狀態是如何在整個系統的更新中反映出來的,在咱們的特定上下文中,變化的狀態如何反映到dom的變化中。數據模型僅僅是普通的 JavaScript 對象。而當你修改它們時,視圖會進行更新。java

<body>
  <span class="cell b"></span>
</body>
<script> let state = { a: 1 } const onStateChange = (() => { document.querySelector('.cell').textContent = state.a * 10 }) </script>
複製代碼

在這個僞代碼中,咱們設置了一個變量state,和一個onStateChange函數,其做用時在state發生變化時可以對視圖進行更新。 咱們進一步抽象,抽象出這個命令式的DOM到一個模板語言裏node

<body>
  <span class="cell b">
    {{state.a*10}}
  </span>
</body>
<script> let update; // we can understand this to Observer update const onStateChange = _update => { update = _update } const setState = newState => { state = newState; update() } onStateChange(()=>{ view = render(state) }) setState({a:5}) </script>
複製代碼

若是你用過react,你會發現它很是熟悉,由於React會在setState中強制觸發狀態改變,在angular環境中,咱們能夠直接操做狀態,由於angular使用了髒檢查,他攔截你的事件,好比單擊以執行digest循環而後檢查全部的東西是否改變了。react

<body>
  <span class="cell b">
    {{state.a*10}}
  </span>
</body>
<script> let update; // we can understand this to Observer update let state = { a: 1 } const onStateChange = _update => { update = _update } onStateChange(() => { view = render(state) }) state.a = 5 </script>
複製代碼

在視圖聯繫中Vue作的更細緻,將State對象轉換爲響應式的,經過使用Object.defineProperty,咱們將全部這些屬性轉換成getter和setter,因此咱們對state.a來講,把a轉換成一個getter和setter。當咱們對a的值進行設置時,去觸發onStateChange。web

2、實現一個小型數據監聽器

getter、setter

首先咱們須要瞭解Object.defineProperty()語法。 算法

在這裏插入圖片描述

function isObject (obj) {
  return typeof obj === 'object'
    && !Array.isArray(obj)
    && obj !== null
    && obj !== undefined
}

function convert (obj) {
  if (!isObject(obj)) {
    throw new TypeError()
  }

  Object.keys(obj).forEach(key => {
    let internalValue = obj[key]
    Object.defineProperty(obj, key, {
      get () {
        console.log(`getting key "${key}": ${internalValue}`)
        return internalValue
      },
      set (newValue) {
        console.log(`setting key "${key}" to: ${newValue}`)
        internalValue = newValue
      }
    })
  })
}

const state = { foo: 123 }
convert(state)

state.foo // should log: 'getting key "foo": 123'
state.foo = 234 // should log: 'setting key "foo" to: 234'
state.foo // should log: 'getting key "foo": 234'
複製代碼

觀察者模式

觀察者模式是咱們要了解的第二個知識點express

當對象間存在一對多關係時,則使用觀察者模式(Observer Pattern)。好比,當一個對象被修改時,則會自動通知依賴它的對象。觀察者模式屬於行爲型模式。數組

  • 意圖:定義對象間的一種一對多的依賴關係,當一個對象的狀態發生改變時,全部依賴於它的對象都獲得通知並被自動更新。

  • 主要解決:一個對象狀態改變給其餘對象通知的問題,並且要考慮到易用和低耦合,保證高度的協做。

  • 什麼時候使用:一個對象(目標對象)的狀態發生改變,全部的依賴對象(觀察者對象)都將獲得通知,進行廣播通知。

  • 如何解決:使用面向對象技術,能夠將這種依賴關係弱化。

  • 關鍵代碼:在抽象類裏有一個 ArrayList 存放觀察者們。

    在這裏插入圖片描述
    咱們來簡單實現一個觀察者模式

<script> class Dep { constructor() { this.state = 0; this.observers = [] } getState() { return this.state } setState(state) { this.state = state; this.notify() } notify() { this.observers.forEach(observer => observer.update()) } addDep(observer) { this.observers.push(observer) } } class Watcher { constructor(name, dep) { this.name = name this.dep = dep this.dep.addDep(this) } update() { console.log(`${this.name}update,state:${this.dep.getState()}`) } } let dep = new Dep() let watch = new Watcher('dep', dep) dep.setState(2312) </script>
複製代碼

有了以上的鋪墊,咱們就能夠實現一個簡單的數據監聽器

<script> class Vue { constructor(options) { this.$options = options; // 數據響應式處理 this.$data = options.data; this.observe(this.$data); // 測試: 沒有編譯器,寫僞碼 new Watcher(this, 'test') this.test new Watcher(this, 'foo.bar') this.foo.bar if (options.created) { options.created.call(this); } } observe(value) { // 但願傳進來的是對象 if (!value || typeof value !== 'object') { return; } // 遍歷data屬性 Object.keys(value).forEach(key => { this.defineReactive(value, key, value[key]) // 代理,能夠經過vm.xx訪問data中的屬性 this.proxyData(key); }) } // 每個屬性都有一個Dep蒐集觀察者 defineReactive(obj, key, val) { // 製造閉包 // 遞歸 this.observe(val); // 建立一個對應的Dep const dep = new Dep(); // 監聽的屬性 // 給obj定義屬性 Object.defineProperty(obj, key, { get() { // 將Dep.target(wather)收集起來,每當有一個新watcher當即蒐集 Dep.target && dep.addDep(Dep.target); return val; }, set(newVal) { if (newVal === val) { return; } val = newVal; // console.log(`${key}屬性更新了`); // 更新視圖操做 dep.notify(); }, }) } proxyData(key) { // 給KVue實例指定屬性 Object.defineProperty(this, key, { get() { return this.$data[key]; }, set(newVal) { this.$data[key] = newVal; } }) } } // 管理若干Watcher實例,它和data中的屬性1:1關係 class Dep { constructor() { this.watchers = []; } // 新增watcher addDep(watcher) { this.watchers.push(watcher) } // 通知變動 notify() { this.watchers.forEach(watcher => watcher.update()) } } // 監聽器: 負責更新頁面中的具體綁定 // 觀察誰 // 怎麼更新,callback class Watcher { // vm是KVue實例 // key是data中的一個屬性 constructor(vm, key, cb) { this.vm = vm; this.key = key; this.cb = cb; // autoRun Dep.target = this; this.vm[this.key]; // 讀取觸發依賴收集 Dep.target = null; } update() { // console.log(this.key+'更新了'); this.cb.call(this.vm, this.vm[this.key]) } } </script>
複製代碼

3、Vue是如何實現響應式的

vue1響應式, Objec.t.defineProperty每一個數據修改,都能通知dom去改變 vue2x中響應式的級別修改了, watcher只到組件級,組件內部使用虛擬dom

接下來咱們詳細的說說Vue是如何實現響應式的

在這裏插入圖片描述

3.一、API介紹

initState

Vue初始化的時候,會調用initState.,它會初始化data,props等,這裏咱們重點看data初始化

// src/core/instance/state
export function initState (vm: Component) {
  vm._watchers = []
  const 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)
  }
}
複製代碼

initData

initData核心代碼是data數據響應化

function initData (vm: Component) {
  let data = vm.$options.data
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  // 把data代理到實例上
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    proxy(vm, `_data`, key)
  }
  // observe data
  observe(data, true /* asRootData */)
}
複製代碼

observe

observe方法返回一個Observer實例

/** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */
export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  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
}
複製代碼

Observer

Observer對象根據數據類型執行對應的響應化操做

/** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */
export class Observer {
  value: any;
  dep: Dep;// 保存數組類型數據的依賴
  vmCount: number; // number of vms that have this object as root $data

  constructor (value: any) {
    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)
    }
  }

  /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. * 若是是對象,則執行該函數 */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

  /** * Observe a list of Array items. */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}
複製代碼

defineReactive

defineReactive定義對象的getter/setter

**
 * Define a reactive property on an Object.
 */
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()
        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()
    }
  })
}


複製代碼

Dep

Dep負責管理一組Watcher,包括watcher實例的增刪及通知更新

/** * A dep is an observable that can have multiple * directives subscribing to it. */
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)
  }
  // 調用watcher的adddep方法實現watcher和dep相互引用
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}

// The current target watcher being evaluated.
// This is globally unique because only one watcher
// can be evaluated at a time.
Dep.target = null
複製代碼

Watcher的構造函數 解析一個表達式並蒐集依賴,當數值發生變化出發回調函數,經常使用於$watch API和指令中。每一個組件也會有對應的Watcher,數值變化會觸發其update函數致使從新渲染

在這裏插入圖片描述

export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  lazy: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  deps: Array<Dep>;
  newDeps: Array<Dep>;
  depIds: SimpleSet;
  newDepIds: SimpleSet;
  before: ?Function;
  getter: Function;
  value: any;

  constructor (
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    this.vm = vm
    // 組件保存render watcher
    if (isRenderWatcher) {
      vm._watcher = this
    }
    // 組件保存非render watcher
    vm._watchers.push(this)
    // parse expression for getter
    // 將表達式解析爲getter函數
    // 若是是函數則直接指定爲getter,何時是函數?
    // 答案是那些和組件實例對應的Watcher建立時會傳遞組件更新函數updateComponent
    if (typeof expOrFn === 'function') {
      this.getter = expOrFn
    } else {
     // 這種是$watch傳遞進來的表達式,須要被解析爲函數
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }

  /** * Evaluate the getter, and re-collect dependencies. * 模擬getter。從新蒐集依賴 */
  get () {
    // Dep.target = this
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      // 從組件中獲取到value同時觸發依賴蒐集
      value = this.getter.call(vm, vm)
    } catch (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
  }

  /** * Add a dependency to this directive. */
  addDep (dep: Dep) {
    const id = dep.id
    if (!this.newDepIds.has(id)) {
      this.newDepIds.add(id)
      this.newDeps.push(dep)
      if (!this.depIds.has(id)) {
        dep.addSub(this)
      }
    }
  }

  /** * Clean up for dependency collection. */
  cleanupDeps () {
    let i = this.deps.length
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }

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

  /** * Scheduler job interface. * Will be called by the scheduler. */
  run () {
    if (this.active) {
      const 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
        const oldValue = this.value
        this.value = value
        if (this.user) {
          try {
            this.cb.call(this.vm, value, oldValue)
          } catch (e) { }
        } else {
          this.cb.call(this.vm, value, oldValue)
        }
      }
    }
  }


  /** * Depend on all deps collected by this watcher. */
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend()
    }
  }

}

複製代碼

vue中的數據響應化使用了觀察者模式:

  • defineReactive中的getter和setter對應着訂閱和發佈行爲
  • Dep的角色至關於主題Subject,維護訂閱者、通知觀察者更新
  • Watcher的角色至關於觀察者Observer,執行更新可是vue裏面的
  • Observer不是上面說的觀察者,它和data中對象-對應,有內嵌的對象就會有childObserver與之對應

$watch

$watch是一個和數據響應式息息相關的API,它指一個監控表達式,當數值發生變化的時候執行回調函數

Vue.prototype.$watch = function ( expOrFn: string | Function, cb: any, options?: Object ): Function {
    const vm: Component = this
    if (isPlainObject(cb)) {
      return createWatcher(vm, expOrFn, cb, options)
    }
    options = options || {}
    options.user = true
    const watcher = new Watcher(vm, expOrFn, cb, options)
    if (options.immediate) {
      try {
        cb.call(vm, watcher.value)
      } catch (error) {
        handleError(error, vm, `callback for immediate watcher "${watcher.expression}"`)
      }
    }
    return function unwatchFn () {
      watcher.teardown()
    }
  }
複製代碼

數組響應化

數組⽐較特別,它的操做⽅法不會觸發setter,須要特別處理。修改數組7個變動⽅法使其能夠發送更新通知

methodsToPatch.forEach(function(method) {
	// cache original method
	const original = arrayProto[method]
	def(arrayMethods, method, function mutator(...args) {
		//該⽅法默認⾏爲
		const result = original.apply(this, args)
		//獲得observer
		const ob = this.__ob__
		let inserted
		switch (method) {
			case 'push':
			case 'unshift':
				inserted = args
				break
			case 'splice':
				inserted = args.slice(2)
				break
		}
		if (inserted) ob.observeArray(inserted)
		// 額外的事情是通知更新
		ob.dep.notify()
		return result
	})
})
複製代碼

3.二、響應式流程

$mount—— src\platforms\web\runtime\index.js

掛載時執⾏mountComponent,將dom內容追加⾄el

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

mountComponent ——core/instance/lifecycle

建立組件更新函數,建立組件watcher實例

updateComponent = () => {
	 // ⾸先執⾏vm._render() 返回VNode,在這一環節進行依賴蒐集
	 // 而後VNode做爲參數執⾏update作dom更新
	 vm._update(vm._render(), hydrating)
 }
new Watcher(vm, updateComponent, noop, {
	 before () {
		 if (vm._isMounted && !vm._isDestroyed) {
		 	callHook(vm, 'beforeUpdate')
		 }
    }
 }, true /* isRenderWatcher */)
複製代碼

_render() ——src\core\instance\render.js

獲取組件vnode。依賴蒐集 每一個屬性都要有一個dep,每一個dep中存放着watcher,同一個watcher會被多個dep所記錄。這個watcher對應着咱們在mountComponent函數建立的watcher

const { render, _parentVnode } = vm.$options;
vnode = render.call(vm._renderProxy, vm.$createElement);
複製代碼

_update src\core\instance\lifecycle.js

執⾏patching算法,初始化或更新vnode⾄$el

if (!prevVnode) {
 // initial render
 // 若是沒有⽼vnode,說明在初始化
 vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
 } else {
 // updates
 // 更新週期直接diff,返回新的dom
 vm.$el = vm.__patch__(prevVnode, vnode)
 }
複製代碼

patch ——src\platforms\web\runtime\patch.js

定義組件實例補丁⽅法

Vue.prototype.__patch__ = inBrowser ? patch : noop
複製代碼

createPatchFunction ——src\core\vdom\patch.js

建立瀏覽器平臺特有patch函數,主要負責dom更新操做

// 擴展操做:把通⽤模塊和瀏覽器中特有模塊合併
const modules = platformModules.concat(baseModules)
// ⼯⼚函數:建立瀏覽器特有的patch函數,這⾥主要解決跨平臺問題
export const patch: Function = createPatchFunction({ nodeOps, modules })
複製代碼

最後

若是你有不清楚的地方或者認爲我有寫錯的地方,歡迎評論區交流。

相關文章
相關標籤/搜索