Vue深刻響應式原理源碼分析(上)

Vue.js實現響應式的核心是利用了es5的object.defineProperty,這也是vue.js不能兼容ie8及如下瀏覽器的緣由。html

Object.defineProperty

Object.defineProperty方法會直接在一個對象上定義一個新屬性,或者修改一個對象的現有屬性,並返回這個對象,看下它的語法:vue

Object.defineProperty(obj,prop,descriptor)react

obj是要在其上定義屬性的對象;prop是要定義或修改的屬性的名稱;descriptor是將被定義或修改的屬性描述符。descriptor裏有不少可選鍵值,咱們最關心的是get和set,get是一個給屬性提供的getter方法,當咱們訪問了該屬性的時候會觸發getter方法;set是一個給屬性提供的setter方法,當咱們對該屬性作修改的時候會觸發setter方法。一旦對象擁有了getter和setter,咱們能夠簡單地把這個對象稱爲響應式對象。express

initState

在Vue的初始化階段,_init方法執行的時候,會執行initState(vm)方法,它的定義在src/core/instance/state.js中。api

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)
  }
}
複製代碼

initState方法主要是對props、methods、data、computed和watcher等屬性作了初始化操做。這裏咱們重點分析下props和data,數組

initProps
function initProps (vm: Component, propsOptions: Object) {
  const propsData = vm.$options.propsData || {}
  const props = vm._props = {}
  // cache prop keys so that future props updates can iterate using Array
  // instead of dynamic object key enumeration.
  const keys = vm.$options._propKeys = []
  const isRoot = !vm.$parent
  // root instance props should be converted
  if (!isRoot) {
    toggleObserving(false)
  }
  for (const key in propsOptions) {
    keys.push(key)
    const value = validateProp(key, propsOptions, propsData, vm)
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      const hyphenatedKey = hyphenate(key)
      if (isReservedAttribute(hyphenatedKey) ||
          config.isReservedAttr(hyphenatedKey)) {
        warn(
          `"${hyphenatedKey}" is a reserved attribute and cannot be used as component prop.`,
          vm
        )
      }
      defineReactive(props, key, value, () => {
        if (vm.$parent && !isUpdatingChildComponent) {
          warn(
            `Avoid mutating a prop directly since the value will be ` +
            `overwritten whenever the parent component re-renders. ` +
            `Instead, use a data or computed property based on the prop's ` + `value. Prop being mutated: "${key}"`, vm ) } }) } else { defineReactive(props, key, value) } // static props are already proxied on the component's prototype
    // during Vue.extend(). We only need to proxy props defined at
    // instantiation here.
    if (!(key in vm)) {
      proxy(vm, `_props`, key)
    }
  }
  toggleObserving(true)
}
複製代碼

props的初始化主要過程,就是遍歷定義的props配置。遍歷的過程主要作兩件事,一是調用defineReactive方法把每一個prop對應的值變成響應式,能夠經過vm._props.xxx訪問到定義props中對應的屬性。另外一個是經過proxy把vm._props.xxx的訪問代理到vm.xxx上。瀏覽器

initData
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
  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
  observe(data, true /* asRootData */)
}
複製代碼

拿到option.data賦值給vm._data變成一個對象,而後遍歷全部的keys值,而後在某些狀況下報一些警告,而後把_data上的東西代理到咱們的vm實例上。另外調用observe觀測整個data的變化,把data也變成響應式,能夠經過vm._data.xxx訪問到定義data返回函數中對應的屬性。bash

proxy

代理的做用是把props和data上的屬性代理到vm實例上,這也就是爲何咱們定義了以下props,卻能夠經過vm實例訪問到它。markdown

let test = {
    props:{
        msg:'hello world'
    },
    methods:{
        getTest(){
            console.log(this.msg)
        }
    }
}
複製代碼

咱們在getTest函數中經過this.msg訪問到咱們定義的props中的msg,這個過程發生在proxy階段:ide

const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  }
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val
  }
  Object.defineProperty(target, key, sharedPropertyDefinition)
}

複製代碼

經過Object.defineProperty把target[sourceKey][key]的讀寫變成了對target[key]的讀寫。因此對於props而言,對vm._props.xxx的讀寫變成了vm.xxx的讀寫,而對於vm.xxx訪問定義在props中的xxx屬性了。同理對於data而言,對vm._data.xxxx的讀寫變成了對vm.xxxx的讀寫,而對於vm._data.xxxx的讀寫,咱們能夠訪問到定義在data函數返回對象中的屬性,因此咱們就能夠經過vm.xxxx訪問到定義在data函數返回對象中的xxxx屬性了。

observe

observe的功能就是用來監測數據的變化,它的定義在src/core/observer/index.js中:

/**
 * 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
}
複製代碼

observe接收兩個值,一個是value,任意類型的一個是asRootData,在initData中調用observe

observe(data,true)

傳入的是定義的data的這個對象,而後調用observe這個函數後,先判斷value是否是一個object,若是是一個object而且是一個VNode,這兩個條件都知足的狀況下,直接返回。接着判斷value是否有__ob__這個屬性,若是有的話而且是Observer這個實例, 直接拿到ob而且返回,不然的話判斷幾個條件,第一個是shouldObserve,這個shouldObserve在全局中定義了

export let shouldObserve: boolean = true 
    export function toggleObserving (value: boolean) {
      shouldObserve = value
    }
複製代碼

shouldObserve會經過toggleObserving這個方法來修改值。第二個是!isServerRendering()而且要麼是一個數組要麼是一個對象,而且是這個對象是可擴展的一些屬性,最後還要判斷它不是一個vue, 知足了以上這些個條件纔會去實例化observe。

Observer

Observer是一個類,它的做用是給對象的屬性添加getter和setter,用於依賴收集和派發更新

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that has 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)) {
      const augment = hasProto
        ? protoAugment
        : copyAugment
      augment(value, arrayMethods, arrayKeys)
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }

  /**
   * Walk through each property 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])
    }
  }
}
複製代碼

new Observe的時候會執行這個構造函數,而後保留這個value,實例化Dep,而後調用def,

/**
 * Define a property.
 */
export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}
複製代碼

def呢就是把Object.defineProperty作一次封裝。在這裏它的目標呢是給value,添加一個__ob__屬性,而且這個屬性的值呢指向當前的這個實例,而後對value進行判斷是不是數組,而後調用observeArray方法

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

遍歷數組中的每一個元素,而後遞歸調用observe。

若是數組是一個對象,就會調用walk方法,

walk (obj: Object) {
   const keys = Object.keys(obj)
   for (let i = 0; i < keys.length; i++) {
     defineReactive(obj, keys[i])
   }
 }
複製代碼

walk方法呢很簡單,遍歷對象上的全部屬性,而後調用defineReactive

defineReactive

defineReactive的功能就是定義一個響應式對象,給對象動態添加getter和setter,

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

defineReactive函數最開始初始化Dep對象的實例,接着拿到obj的屬性描述符,而後對子對象遞歸調用observe方法,這樣就保住了不管obj的結構多複雜,它的全部子屬性也能變成響應式的對象,這樣咱們訪問或修改obj中一個嵌套較深的屬性,也能觸發getter和setter。最後利用Object.defineProperty去給obj的屬性key添加getter和setter。 咱們來分析下getter的邏輯,getter的過程呢就是完成了依賴收集。首先拿到這個getter,而後去進行getter.call,若是沒有的話就直接用這個val值,而後一段依賴的過程,首先判斷Dep.target是否存在,Dep呢是一個類,咱們來看下,

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()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}
Dep.target = null
const targetStack = []
export function pushTarget (_target: ?Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}
export function popTarget () {
  Dep.target = targetStack.pop()
}

複製代碼

主要功能是創建數據和watcher之間的橋樑。Dep.target是一個全局的watcher,由於同一時間只有一個watcher會被計算,因此target代表了我當前正在被計算的watcher。Dep除了靜態的target屬性還有兩個,id,subs,咱們每建立一個Dep,id都是自增的,subs就是全部的watcher。

Dep實際上就是對watcher的一種管理,Dep脫離wathcer單獨存在是沒有意義的,咱們看一下wathcer的一些相關實現,

let uid = 0
/**
 * A watcher parses an expression, collects dependencies,
 * and fires callback when the expression value changes.
 * This is used for both the $watch() api and directives.
 */
export default class Watcher {
  vm: Component;
  expression: string;
  cb: Function;
  id: number;
  deep: boolean;
  user: boolean;
  computed: boolean;
  sync: boolean;
  dirty: boolean;
  active: boolean;
  dep: Dep;
  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
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      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 = []
    this.depIds = new Set()
    this.newDepIds = new Set()
    this.expression = process.env.NODE_ENV !== 'production'
      ? expOrFn.toString()
      : ''
    // parse expression for getter
    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.value = this.get()
    }
  }

  /**
   * Evaluate the getter, and re-collect dependencies.
   */
  get () {
    pushTarget(this)
    let value
    const 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
  }

  /**
   * 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
  }
  ...
}
複製代碼

watcher是一個Class,在它的構造函數中,定義了一些和Dep相關的屬性:

this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
複製代碼

其中,this.deps和this.newDeps表示watcher實例持有的Dep實例的數組;而this.depIds和this.newDepIds分別表明this.deps和this.newDeps的idSet。 在Vue的mount過程是經過mountComponent函數,

updateComponent = () => {
  vm._update(vm._render(), hydrating)
}
new Watcher(vm, updateComponent, noop, {
  before () {
    if (vm._isMounted) {
      callHook(vm, 'beforeUpdate')
    }
  }
}, true /* isRenderWatcher */)
複製代碼

當咱們去實例化一個渲染watcher的時候,首先進入watcher的構造函數邏輯,而後會執行它的this.get()方法,進入get函數,首先會執行:

pushTarget(this)
複製代碼

pushTarget的定義在src/core/observer/dep.js中:

export function pushTarget (_target: ?Watcher) {
  if (Dep.target) targetStack.push(Dep.target)
  Dep.target = _target
}
複製代碼

實際上就是把Dep.target賦值爲當前的渲染watcher並壓棧,接着又執行了:

value = this.getter.call(vm, vm)
複製代碼

this.getter對應就是updateComponent函數,這實際上就是在執行:

vm._update(vm._render(),hydrating)

它會先執行vm._render()方法,由於以前分析過這個方法會生成渲染VNode,而且在這個過程當中會對vm上的數據訪問,這個時候就觸發了數據對象的getter。那麼每一個對象值的getter都持有一個dep,在觸發getter的時候會調用dep.depend()方法,也就會執行Dep.target.addDep(this)。 剛纔Dep.target已經被賦值爲渲染watcher,那麼就執行到addDep方法:

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)
      }
    }
}
複製代碼

這時候作了一些邏輯判斷而後執行dep.addSub(this),那麼就會執行this.subs.push(sub),也就是說把當前的watcher訂閱到這個數據持有的dep的subs中,這個目的是爲後續數據變化時候能通知到哪些subs作準備的。 因此在vm._render()過程當中,會觸發全部數據的getter,這樣實際上已經完成了一個依賴收集的過程。再完成依賴收集後,還有執行

if(this.deep){
    traverse(value)
}
複製代碼

這個是要遞歸去訪問value,觸發它全部子項的getter,接下來執行

popTarget()

popTarget的定義在src/core/observer/dep.js中

Dep.target = targetStack.pop()

實際上就是把Dep.target恢復和成上一個狀態,由於當前vm的數據依賴收集已經完成,因此對應的渲染Dep.target也須要改變。最後執行:

this.cleanupDeps()

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
  }
複製代碼

考慮到Vue是數據驅動的,因此每次數據變化都會從新render,那麼vm._render()方法又會再次執行,並再次觸發數據的getters,因此watcher在構造函數中會初始化2個Dep實例數組,newDeps表示新添加的Dep實例數組,而deps表示上一次還有加的Dep實例數組。 在執行cleanupDeps函數的時候,會首先遍歷deps,移除對dep的訂閱,而後把newDepIds和depIds交換,newDeps和deps交換,並把newDepIds和newDeps清空。 那麼爲何須要作deps訪問的移除呢,在添加deps的訂閱過程,已經能經過id去重避免重複訂閱了。 考慮一種場景,例如:咱們用v-if去渲染不一樣子模板a、b,當咱們知足某條件渲染a的時候,會訪問到a中的數據,這時候咱們對a使用的數據添加了getter,作了依賴收集,那麼當咱們去修改a的數據的時候,理應通知到這些訂閱者。那麼一旦咱們改變了條件渲染了b模板,又會對b使用的數據添加了getter,若是咱們沒有依賴移除的過程,那麼這時候我去修改a模板的數據,會通知a數據的訂閱的回調,這顯然是有浪費的。 因此Vue設計了在每次添加完新的訂閱,會移除掉舊的訂閱,這樣就保證了在咱們剛纔的場景中,若是渲染b模板的時候去修改a模板的數據,a數據訂閱回調已經被移除了,因此不會有任何浪費。

相關文章
相關標籤/搜索