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数据订阅回调已经被移除了,因此不会有任何浪费。

相关文章
相关标签/搜索