vue源碼之旅-2 - 數據響應式原理的實現

在官方文檔的深入響應式原理這一節可以看到,Vue是通過Object.defineProperty 來定義數據的響應式的, 接着從源碼層面來喵一眼到底是怎麼做的?

src/core/instance/state.js

我簡單注視了一下源碼

/**
 * 1. 調用initData()方法, 初始化用戶傳入的 data 
 * @param {*} vm 
 */
function initData (vm: Component) {
  let data = vm.$options.data // 拿到用戶傳入的數據
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== 'production' && 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
  // 將所有的key 取出來 存到數組裏
  // Object.keys() 會把一個對象中的所有的key 取出來,返回一個由這些key組成的數組
  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]
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && 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
  /**
   * 2. 就是對數據 進行觀測
   */
  observe(data, true /* asRootData */)
}

接着看這個 observe() 方法

src/core/observer/index.js

這段代碼注視的 很清楚, 就是嘗試爲值創建觀察者實例,
主要看這句, new Observer(value) , 把要被觀測的數據 傳入了這個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
}

接着看 Oberver 這個類
src/core/observer/index.js

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

這個類主要是先對觀測的數據 做了一個判斷,

  1. 如果是對象, 就走 this.walk(value) 這個方法

那麼接着看 this.walk() 方法, 這個方法就是先把所有的 key 放到一個數組裏, 然後便利所有的key,調用 defineReactive(), 在這個方法裏, 我們看到了 一個重要的方法Object.defineProperty(), 這個方法就是給所有的key 重新定義響應式,同時給每個key 都加上setter 和 getter, 同時在set數據的時候呢, 還會調用 dep.notify() 更新方法


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

  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()
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}

以上是vue 對 對象的 響應式處理, 那麼是怎麼處理數組類型的數據的呢,

  1. 如果是數組,就是先拷貝數組原型的方法,進行重寫, 然後調用def 方法,最後通知更新

src/core/observer/array.js

/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

import { def } from '../util/index'

const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)

/**
 * Intercept mutating methods and emit events
 */
[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]
.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]
  def(arrayMethods, method, function mutator (...args) {
    const result = original.apply(this, args)
    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)
    // notify change
    ob.dep.notify()
    return result
  })
})

總結:

  1. 先調用 initData() 方法, 初始化用戶傳入的data,然後對這些數據 進行 觀測, 也就是new Oberser()
  2. 接着 會判斷這個數據類型是對象,還是數組, 如果是對象就便利所有的key , 調用 defineReactive() 方法,重新定義數據, 添加響應式, 給個key 都添加setter 和 getter,多層結構時進行遞歸
  3. 使用函數劫持的方式,重寫了數組的方法
    Vue 將 data 中的數組,進行了原型鏈重寫。指向了自己定義的數組原型方法,這樣當調用數組 api 時,可以通知依賴更新.如果數組中包含着引用類型。會對數組中的引用類型再次進行監控。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章