Vue源码解读(三):响应式原理

Vue 一大特点就是数据响应式,数据的变化会作用于视图而不用进行 DOM 操作。原理上来讲,是利用了 Object.defifineProperty(),通过定义对象属性 setter 方法拦截对象属性的变更,从而将属性值的变化转换为视图的变化。
在 Vue 初始化时,会调用 initState ,它会初始化 propsmethodsdata computedwatch 等.

响应式对象

initState

// src/core/instance/state.js
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)
  }
}

initProps

// src/core/instance/state.js
function initProps (vm: Component, propsOptions: Object) {
  const propsData = vm.$options.propsData || {}
  const props = vm._props = {}
  // 缓存 props 的每个 key,性能优化
  const keys = vm.$options._propKeys = []
  const isRoot = !vm.$parent
  // root instance props should be converted
  // 非根实例的情况
  if (!isRoot) {
    // 响应式的优化,主要优化在响应式处理的递归过程
    toggleObserving(false)
  }
  for (const key in propsOptions) {
    // 缓存 key
    keys.push(key)
    // 校验并返回值,主要检查传递的数据是否符合 prop 的定义规范
    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
        )
      }
      // 为 props 的每个 key 设置响应式
      defineReactive(props, key, value, () => {
        if (!isRoot && !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 {
      // 为 props 的每个 key 设置响应式
      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 的初始化就是对其进行遍历,遍历过程主要做两件事:

  • 调用 defineReactive 对每个值做响应式处理。
  • 通过 proxyvm._props.xxx 的访问代理到 vm.xxx 上。

initData

// src/core/instance/state.js
function initData (vm: Component) {
  let data = vm.$options.data
  // 判断 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
    )
  }
  // 代理数据到 vm 实例上。
  // 判断去重, data 上的属性不能和 props、methods 上的属性相同。
  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, true /* asRootData */)
}
export function getData (data: Function, vm: Component): any {
  // #7573 disable dep collection when invoking data getters
  pushTarget()
  try {
    return data.call(vm, vm)
  } catch (e) {
    handleError(e, vm, `data()`)
    return {}
  } finally {
    popTarget()
  }
}

data 的初始化和 props 目的差不多,这里主要做了三件事:

  • 检查 data 上的属性不能和 propsmethods 上的属性相同。
  • 通过 proxyvm._data.xxx 的访问代理到 vm.xxx 上。
  • 调用 observedata 上的数据变成响应式。

proxy

// src/core/instance/state.js
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)
}

代理的作用是把 props 和 data 上的属性代理到 vm 实例上,这就是为什么我们定义了 props.xxx,却可以通过 this.xxx 进行访问。

observe

// src/core/observer/index.js
export function observe (value: any, asRootData: ?boolean): Observer | void {
  // 非对象和 VNode 实例不做响应式处理
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    // 如果 value 对象上存在 __ob__ 属性,则表示已经做过观察了,直接返回 __ob__ 属性
    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 就是给非 VNode 的对象类型创建观察者实例 Observer,如果已观察成功,直接返回已有的观察者,否则创建新的实例。

Observer

// src/core/observer/index.js
/**
 * Observer class that is attached to each observed
 * nce 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
    // 为什么在 Observer 里面声明 Dep?
    this.dep = new Dep()
    this.vmCount = 0
    // 在 value 对象上设置 __ob__ 属性,引用了当前 Observer 实例
    def(value, '__ob__', this)
    // 判断类型
    if (Array.isArray(value)) {
      // 覆盖数组默认的七个原型方法,以实现数组响应式
      // hasProto = '__proto__' in {}
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }
  /**
   * 遍历对上的每个 key,设置响应式
   * 只有类型为 Object 时才走到这里
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }
  /**
   * 如果数组里面的值还是对象,则还需要做响应式处理
   */
  observeArray (items: Array<any>) {
    for (let i = 0, l = items.length; i < l; i++) {
      observe(items[i])
    }
  }
}

Observer 类会被附加到被观察的对象上,也就是说,每一个响应式对象上都会有一个 __ob__;然后对数据类型进行了一个判断;若是数组,则判断是否存在 __proto__ 属性,因为要通过原型链覆盖数组的几个方法,判断有无 __proto__ 属性,主要是一种兼容的处理方式,__proto__ 不是标准属性,所以有些浏览器不支持,比如 IE6-10,Opera10.1。

为什么在 Observer 里面声明 Dep? 了解过响应式的道友都知道,我们应该是一个 key 对应一个 dep 嘛,来管理依赖,当 key 的值发生变化时,触发 setter 通知更新。这里的 dep 主要是作用于 Object 属性增加和删除,Array 的变更方法。比如: { a: { b: 1 } } 使用了 $set 增加了一个属性 { a: { b: 1, c: 2 } } ,不管 a.b 还是 a.c ,增加还是删除,只要是和 a 相关的,就直接更新。具体哪些有变化,需要真正的更新,交给 diff 老哥。这里不了解的道友,可以看完整个响应式再来回顾。

defineReactive

// src/core/observer/index.js
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  // 实例化 dep,一个 key 一个 dep
  const dep = new Dep()
  // 获取 obj[key] 的属性描述符,发现它是不可配置对象的话直接 return
  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }
  // 记录 getter 和 setter,获取 val 值
  const getter = property && property.get
  const setter = property && property.set
  if ((!getter || setter) && arguments.length === 2) {
    val = obj[key]
  }
  // 递归调用,处理 val 的值为对象的情况
  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    // 劫持读取操作
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      // Dep.target 是 Dep的一个静态属性,保存的是当前的 Watcher 实例。
      // 在 new Watcher 实例化的时候(computed 除外,因为它懒执行)会触发读取造作,被劫持运行这个 get 函数,进行依赖收集。
      // 在实例化 Watcher 最后,Dep.target 设置为 null,避免重复收集。
      if (Dep.target) {
        // 依赖收集,在 dep 中添加 watcher,也在 watcher 中添加 dep
        dep.depend()
        // childOb 表示当前的 val 还是一个复杂类型,对象或者数组。
        if (childOb) {
          // 这个 dep 是在 Observer中创建的,之前提到过。
          childOb.dep.depend()
          if (Array.isArray(value)) {
            // 处理数组内还是对象的情况
            dependArray(value)
          }
        }
      }
      return value
    },
    // 劫持修改操作
    set: function reactiveSetter (newVal) {
      // 旧的 obj[key] 
      const value = getter ? getter.call(obj) : val
      // 如果新旧值一样,则直接 return,无需更新
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      // setter 不存在说明该属性是一个只读属性,直接 return
      if (getter && !setter) return
      // 设置新值
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      // 对新值进行观察,让新值也是响应式的
      childOb = !shallow && observe(newVal)
      // 依赖通知更新
      dep.notify()
    }
  })
}
// src/core/observer/index.js
/**
 * 遍历每个数组元素,递归处理数组项为对象的情况,为其添加依赖.
 * 因为前面的递归阶段无法为数组中的对象元素添加依赖.
 */
function dependArray (value: Array<any>) {
  for (let e, i = 0, l = value.length; i < l; i++) {
    e = value[i]
    e && e.__ob__ && e.__ob__.dep.depend()
    if (Array.isArray(e)) {
      dependArray(e)
    }
  }
}

defineReactive 的作用就是利用 Object.defineProperty 对数据的读写进行劫持,给属性 key 添加 gettersetter ,用于依赖收集和通知更新。如果传进来的值依旧是一个对象,则递归调用 observe 方法,保证子属性都能变成响应式。

依赖收集

Dep

//  src/core/observer/dep.js
/* @flow */
import type Watcher from './watcher'
import { remove } from '../util/index'
import config from '../config'
let uid = 0
/**
 * 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 = []
  }
  // 添加订阅,把 Watcher实例,保存到 subs中
  addSub (sub: Watcher) {
    this.subs.push(sub)
  }
  // 移除订阅,把 Watcher实例,从 subs 中移除
  removeSub (sub: Watcher) {
    remove(this.subs, sub)
  }
  // 向 Watcher 中添加 dep
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }
  // 通知更新
  notify () {
    // stabilize the subscriber list first
    const subs = this.subs.slice()
    if (process.env.NODE_ENV !== 'production' && !config.async) {
      // subs aren't sorted in scheduler if not running async
      // we need to sort them now to make sure they fire in correct
      // order
      subs.sort((a, b) => a.id - b.id)
    }
    // 遍历 dep 中存储的 watcher,执行 watcher.update()
    for (let i = 0, l = subs.length; i < l; i++) {
      subs[i].update()
    }
  }
}
/**
 * 当前正在执行的 watcher,同一时间只会有一个 watcher 在执行
 * Dep.target = 当前正在执行的 watcher ,并推入栈中
 * 通过调用 pushTarget 方法完成赋值,调用 popTarget 方法完成重置
 */
Dep.target = null
const targetStack = []
export function pushTarget (target: ?Watcher) {
  targetStack.push(target)
  Dep.target = target
}
export function popTarget () {
  targetStack.pop()
  Dep.target = targetStack[targetStack.length - 1]
}

Watcher

// src/core/observer/watcher.js
/* @flow */
import {
  warn,
  remove,
  isObject,
  parsePath,
  _Set as Set,
  handleError,
  invokeWithErrorHandling,
  noop
} from '../util/index'
import { traverse } from './traverse'
import { queueWatcher } from './scheduler'
import Dep, { pushTarget, popTarget } from './dep'
import type { SimpleSet } from '../util/index'
let uid = 0
/**
 * 一个组件一个 watcher(渲染 watcher)或者一个表达式一个 watcher(用户watcher)
 * 当数据更新时 watcher 会被触发,访问 this.computedProperty 时也会触发 watcher
 */
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
    if (isRenderWatcher) {
      vm._watcher = this
    }
    vm._watchers.push(this)
    // options
    if (options) {
      this.deep = !!options.deep
      this.user = !!options.user
      this.lazy = !!options.lazy
      this.sync = !!options.sync
      this.before = options.before
    } else {
      this.deep = this.user = this.lazy = this.sync = false
    }
    this.cb = cb
    this.id = ++uid // uid for batching
    this.active = true
    this.dirty = this.lazy // for lazy 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 = function() { return this.xx }
      // 在 this.get 中执行 this.getter 时会触发依赖收集
      // 待后续 this.xx 更新时就会触发响应式
      this.getter = parsePath(expOrFn)
      if (!this.getter) {
        this.getter = noop
        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
        )
      }
    }
    this.value = this.lazy
      ? undefined
      : this.get()
  }
  /**
   * 执行 this.getter,并重新收集依赖
   * this.getter 是实例化 watcher 时传递的第二个参数,一个函数或者字符串,比如:updateComponent 或者 parsePath 返回的读取 this.xx 属性值的函数
   * 为什么要重新收集依赖?
   *   因为触发响应式数据更新时,虽然已经经过 observe 观察,但却没有进行依赖收集,
   *   所以,在更新页面时,会重新执行一次 render 函数,执行期间会触发读取操作,这时候进行依赖收集
   */
  get () {
    // 在需要进行依赖收集的时候调用
    // 设置  targetStack.push(target) 和 Dep.target = watcher
    pushTarget(this)
    let value
    const vm = this.vm
    try {
      // 执行回调函数,比如 updateComponent,进入 patch 阶段
      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)
      }
      // 依赖收集结束调用
      // 设置 targetStack.pop() 和 targetStack[targetStack.length - 1]
      popTarget()
      // 清除依赖
      this.cleanupDeps()
    }
    return value
  }
  /**
   * 添加 dep 到 watcher
   * 添加 watcher 到 dep
   */
  addDep (dep: Dep) {
    const id = dep.id
    if (!this.newDepIds.has(id)) {
      // 保存 id 用于去重
      this.newDepIds.add(id)
      // 添加 dep 到当前 watcher
      this.newDeps.push(dep)
      // 避免在 dep 中重复添加 watcher
      if (!this.depIds.has(id)) {
        // 添加当前 watcher 到 dep
        dep.addSub(this)
      }
    }
  }
  /**
   * 清除依赖,每次数据变化都会重新 render, 
   * 那么 vm._render() 方法又会再次执行,并再次触发数据的 getters,所以 Watcher 在构造函数中会初始化 2 个 Dep 实例数组.
   * this.deps 表示上一次的 dep 实例数组,this.newDeps 表示新添加的 dep 实例数组。
   */
  cleanupDeps () {
    let i = this.deps.length
    // 遍历 deps,移除对 dep.subs 数组中 Wathcer 的订阅
    while (i--) {
      const dep = this.deps[i]
      if (!this.newDepIds.has(dep.id)) {
        dep.removeSub(this)
      }
    }
    // newDepIds 和 depIds 做交换,然后清空 newDepIds
    let tmp = this.depIds
    this.depIds = this.newDepIds
    this.newDepIds = tmp
    this.newDepIds.clear()
    // newDeps 和 deps 做交换,然后清空 newDeps
    tmp = this.deps
    this.deps = this.newDeps
    this.newDeps = tmp
    this.newDeps.length = 0
  }
  
  // ... 下面还有几个方法,暂时不看,放在别的地方一块看
}

依赖收集流程

回顾一下在执行 mount 挂载过程中 mountComponent 里有这么一段逻辑。

// src/core/instance/lifecycle.js
  updateComponent = () => {
    vm._update(vm._render(), hydrating)
  }
  
  new Watcher(vm, updateComponent, noop, {
    before () {
      if (vm._isMounted && !vm._isDestroyed) {
        callHook(vm, 'beforeUpdate')
      }
    }
  }, true /* isRenderWatcher */)

收集流程:

  1. 当实例化 Watcher 时,会执行 Watcher 构造函数中的 this.get()
  2. get 中首先调用 pushTarget(this), 其实就是 Dep.target = 当前正在执行的 Watcher 并推入栈中。
  3. 然后执行 value = this.getter.call(vm, vm)
  4. this.getter 对应的就是 updateComponent,实际执行的是 vm._update(vm._render(), hydrating);它会先调用 vm._render()
  5. vm._render() 的作用就是生成 VNode,过程中会触发对数据的访问,也就是触发了 getter.
  6. 每个对象的 key 都会有一个对应的 dep,在 getter 中会调用 dep.depend(),也就会调用 Dep.target.addDep(this);因为在第2步时 Dep.target = 当前正在执行的 Watcher,所以调用的应该是 当前正在执行的 Watcher.addDep(this)
  7. addDep 中在不重复的情况下调用 dep.addSub(this),也就会执行 this.subs.push(sub) ,也就是把 Watcher 实例保存到 depsubs 中。
  8. vm._render() 过程中,会触发所有数据的 getter,这样实际就完成了依赖收集的过程,但是 Watcher 构造函数中的 this.get() 后续还有一些操作。
  9. if (this.deep) { traverse(value) } 要递归去访问 value,触发它所有子项的 getter
  10. 然后执行 popTarget() , 依赖收集结束,重新设置 Dep.target
  11. 最后就是调用 this.cleanupDeps(),清除依赖。

数组响应式

// src/core/observer/index.js
export class Observer {
  // ...
  constructor(value: any) {
    // ...
    if (Array.isArray(value)) {
      // 覆盖数组默认的七个原型方法,以实现数组响应式
      // hasProto = '__proto__' in {}
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
      // ...
    }
  } 
}

还记得上面提到过在 Observer 中有这么一段代码吗?对于类型是数组做了专门的处理。判断 __proto__ 是一种兼容写法,因为有些浏览器不支持。

protoAugment

// src/core/observer/index.js
/**
  * 设置 target.__proto__ 的原型对象为 src
  * 比如 数组对象,arr.__proto__ = arrayMethods
  */
function protoAugment (target, src: Object) {
  /* eslint-disable no-proto */
  target.__proto__ = src
  /* eslint-enable no-proto */
}

copyAugment

// src/core/observer/index.js
/**
 * 通过 def,也就是 Object.defineProperty 去定义它自身的属性值
 * 比如数组:为数组对象定义那七个方法
 */
function copyAugment (target: Object, src: Object, keys: Array<string>) {
  for (let i = 0, l = keys.length; i < l; i++) {
    const key = keys[i]
    def(target, key, src[key])
  }
}

def

// src/core/util/lang.js
export function def (obj: Object, key: string, val: any, enumerable?: boolean) {
  Object.defineProperty(obj, key, {
    value: val,
    enumerable: !!enumerable,
    writable: true,
    configurable: true
  })
}

七个方法

// src/core/observer/array.js
/*
 * 定义 arrayMethods 对象,用于增强 Array.prototype
 * 当访问 arrayMethods 对象上的那七个方法时会被劫持,以实现数组响应式
 */
import { def } from '../util/index'
// 备份 数组 原型对象
const arrayProto = Array.prototype
// 通过继承的方式创建新的 arrayMethods
export const arrayMethods = Object.create(arrayProto)
// 操作数组的七个方法
const methodsToPatch = [
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]
/**
 * 拦截方法并触发事件
 */
methodsToPatch.forEach(function (method) {
  // 缓存原生方法,比如 push
  const original = arrayProto[method]
  // def 就是 Object.defineProperty,劫持 arrayMethods.method 的访问
  def(arrayMethods, method, function mutator (...args) {
    // 先执行原生方法,比如 push.apply(this, args)
    const result = original.apply(this, args)
    const ob = this.__ob__
    // 如果 method 是以下三个之一,说明是新插入了值
    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
  })
})

数组方法重写主要做了这么几件事:

  • arrayMethods 继承了 Array
  • 对数组中能改变数组自身的七个方法进行了劫持和重写,劫持是使其被调用时,调用的是重写后的方法。
  • 重写后的方法首先会调用原来原型上的逻辑。
  • 判断可以添加值的三个方法 pushunshiftsplice ,获取新插入的值,进行响应处理。
  • 最后调用 ob.dep.notify() 通知更新。

$set 和 $delete

在应用中,初始化的时候数据会被设置成响应式。但是响应的数据在初始化的时候就被定义声明。如果对数据添加属性,那么它在初始化的时候是不存在的。比如: { a: { b: 1 } } 增加了一个属性 c -> { a: { b: 1, c: 2 } }, 属性 c 在初始化阶段是不存在的,那么它是如何进行响应式处理的呢?Vue 给我们提供了全局API Vue.setVue.delete 和实例方法 vm.$setvm.$delete 来处理对象属性的添加和删除,确保触发更新视图。来看看几这个方法的定义。

// src/core/global-api/index.js
import { set, del } from '../observer/index'
export function initGlobalAPI (Vue: GlobalAPI) {
  // ...
  Vue.set = set
  Vue.delete = del
}
// src/core/instance/state.js
import {
  set,
  del,
  observe,
  defineReactive,
  toggleObserving
} from '../observer/index'
export function stateMixin (Vue: Class<Component>) {
  // ...
  Vue.prototype.$set = set
  Vue.prototype.$delete = del
}

可以看出全局API Vue.setVue.delete 和实例方法 vm.$setvm.$delete 其实是一样的。

set

// src/core/observer/index.js
/**
 * 通过 Vue.set 或者 this.$set 方法给 target 的指定 key 设置值 val
 * 如果 target 是对象,并且 key 原本不存在,则为新 key 设置响应式,然后执行依赖通知
 */
export function set (target: Array<any> | Object, key: any, val: any): any {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  // 更新数组指定下标的元素,Vue.set(array, idx, val),通过 splice 方法实现响应式更新
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  // 更新对象已有属性,Vue.set(obj, key, val),执行更新即可
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
  const ob = (target: any).__ob__
  // 不能向 Vue 实例或者 $data 添加动态添加响应式属性,vmCount 的用处之一,
  // this.$data 的 ob.vmCount = 1,表示根组件,其它子组件的 vm.vmCount 都是 0
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid adding reactive properties to a Vue instance or its root $data ' +
      'at runtime - declare it upfront in the data option.'
    )
    return val
  }
  // target 不是响应式对象,新属性会被设置,但是不会做响应式处理
  if (!ob) {
    target[key] = val
    return val
  }
  // 给对象定义新属性,通过 defineReactive 方法设置响应式,并触发依赖更新
  defineReactive(ob.value, key, val)
  ob.dep.notify()
  return val
}

del

// src/core/observer/index.js
/**
 * 通过 Vue.delete 或者 vm.$delete 删除 target 对象的指定 key
 * 数组通过 splice 方法实现,对象则通过 delete 运算符删除指定 key,并执行依赖通知
 */
export function del (target: Array<any> | Object, key: any) {
  if (process.env.NODE_ENV !== 'production' &&
    (isUndef(target) || isPrimitive(target))
  ) {
    warn(`Cannot delete reactive property on undefined, null, or primitive value: ${(target: any)}`)
  }
  // target 为数组,则通过 splice 方法删除指定下标的元素
  if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.splice(key, 1)
    return
  }
  const ob = (target: any).__ob__
  // 避免删除 Vue 实例的属性或者 $data 的数据
  if (target._isVue || (ob && ob.vmCount)) {
    process.env.NODE_ENV !== 'production' && warn(
      'Avoid deleting properties on a Vue instance or its root $data ' +
      '- just set it to null.'
    )
    return
  }
  // 如果属性不存在直接结束
  if (!hasOwn(target, key)) {
    return
  }
  // 通过 delete 运算符删除对象的属性
  delete target[key]
  if (!ob) {
    return
  }
  // 执行依赖通知
  ob.dep.notify()
}

methods

initMethods

// src/core/instance/state.js
function initMethods (vm: Component, methods: Object) {
  // 获取 props 配置项
  const props = vm.$options.props
  // 遍历 methods 对象
  for (const key in methods) {
    if (process.env.NODE_ENV !== 'production') {
      if (typeof methods[key] !== 'function') {
        warn(
          `Method "${key}" has type "${typeof methods[key]}" in the component definition. ` +
          `Did you reference the function correctly?`,
          vm
        )
      }
      if (props && hasOwn(props, key)) {
        warn(
          `Method "${key}" has already been defined as a prop.`,
          vm
        )
      }
      if ((key in vm) && isReserved(key)) {
        warn(
          `Method "${key}" conflicts with an existing Vue instance method. ` +
          `Avoid defining component methods that start with _ or $.`
        )
      }
    }
    vm[key] = typeof methods[key] !== 'function' ? noop : bind(methods[key], vm)
  }
}

遍历 methods 对象,然后对每一项进行处理,主要做了这么几件事:

  • 检查 methoss[key] 必须是函数。
  • 检查 methoss[key] 不能与 props 中相同。
  • 检查 methoss[key] 不能与实例上的方法相同,一般是一些内置方法,比如以 $ 和  _ 开头的方法。
  • 将 methods[key] 放到 vm 实例上。

计算属性 vs 侦听属性

computed

// src/core/instance/state.js
const computedWatcherOptions = { lazy: true }
function initComputed (vm: Component, computed: Object) {
  // $flow-disable-line
  const watchers = vm._computedWatchers = Object.create(null)
  // computed properties are just getters during SSR
  const isSSR = isServerRendering()
  // 遍历 computed 对象
  for (const key in computed) {
    /**
     * computed = {
     *   key1: function() { return xx },
     * }
     */
    const userDef = computed[key]
    // getter = function() { return xx }
    const getter = typeof userDef === 'function' ? userDef : userDef.get
    if (process.env.NODE_ENV !== 'production' && getter == null) {
      warn(
        `Getter is missing for computed property "${key}".`,
        vm
      )
    }
    if (!isSSR) {
      // 为 computed 属性创建 watcher 实例,这个是 computed watcher 和渲染 watcher 不同
      watchers[key] = new Watcher(
        vm,
        getter || noop,
        noop,
        // 配置项,computed 默认是懒执行
        computedWatcherOptions
      )
    }
    // component-defined computed properties are already defined on the
    // component prototype. We only need to define computed properties defined
    // at instantiation here.
    if (!(key in vm)) {
      // 代理 computed 对象中的属性到 vm 实例
      defineComputed(vm, key, userDef)
    } else if (process.env.NODE_ENV !== 'production') {
      // computed 的属性不能和 data、props、methods 的属性相同。
      if (key in vm.$data) {
        warn(`The computed property "${key}" is already defined in data.`, vm)
      } else if (vm.$options.props && key in vm.$options.props) {
        warn(`The computed property "${key}" is already defined as a prop.`, vm)
      } else if (vm.$options.methods && key in vm.$options.methods) {
        warn(`The computed property "${key}" is already defined as a method.`, vm)
      }
    }
  }
}
/**
 * 代理 computed 对象中的 key 到 target(vm)上
 */
export function defineComputed (
  target: any,
  key: string,
  userDef: Object | Function
) {
  const shouldCache = !isServerRendering()
  if (typeof userDef === 'function') {
    sharedPropertyDefinition.get = shouldCache
      ? createComputedGetter(key)
      : createGetterInvoker(userDef)
    sharedPropertyDefinition.set = noop
  } else {
    sharedPropertyDefinition.get = userDef.get
      ? shouldCache && userDef.cache !== false
        ? createComputedGetter(key)
        : createGetterInvoker(userDef.get)
      : noop
    sharedPropertyDefinition.set = userDef.set || noop
  }
  if (process.env.NODE_ENV !== 'production' &&
    sharedPropertyDefinition.set === noop) {
    sharedPropertyDefinition.set = function () {
      warn(
        `Computed property "${key}" was assigned to but it has no setter.`,
        this
      )
    }
  }
  // 代理对 computed[key] 的访问和设置 computed[key] 的 get,set
  Object.defineProperty(target, key, sharedPropertyDefinition)
}
/**
 * 返回一个函数做为 computed[key] 的 getter
 */
function createComputedGetter (key) {
  // computed 属性值会缓存的原理也是在这里结合 watcher.dirty、watcher.evalaute、watcher.update 实现的
  return function computedGetter () {
    // 获取 computed[key] 的 computed watcher
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      // 缓存
      if (watcher.dirty) {
        watcher.evaluate()
      }
      // 添加订阅
      if (Dep.target) {
        watcher.depend()
      }
      return watcher.value
    }
  }
}
/**
 * 功能同 createComputedGetter 一样
 */
function createGetterInvoker (fn) {
  return function computedGetter () {
    return fn.call(this, this)
  }
}

从上面代码可以看出,计算属性的初始化主要做了这么几件事情:

  • computed[key] 创建 Watcher 实例。
  • 检查 computed 的属性不能和 datapropsmethods的属性名称相同。
  • 代理 computed[key]vm 是实例上,并设置 getter、setter。

流程分析

前面说到,在计算属性初始化的过程中会为 computed[key] 创建 watcher 的实例,这个 computed watcher 和渲染 watcher 不太一样。在 Watcher 的构造函数中有这么一段逻辑:

// src/core/observer/watcher.js
constructor(
    vm: Component,
    expOrFn: string | Function,
    cb: Function,
    options?: ?Object,
    isRenderWatcher?: boolean
  ) {
    if (options) {
      this.lazy = !!options.lazy
    }
    this.dirty = this.lazy // for lazy watchers
    this.value = this.lazy
      ? undefined
      : this.get()
  }

默认的懒执行,不会立刻求值。
render 函数执行访问到计算属性的时候,也就触发了计算属性的 getter ,也就是 computedGetter 函数:

// src/core/instance/state.js
  return function computedGetter () {
    // 获取 computed[key] 的 computed watcher
    const watcher = this._computedWatchers && this._computedWatchers[key]
    if (watcher) {
      // 缓存
      if (watcher.dirty) {
        watcher.evaluate()
      }
      // 添加订阅
      if (Dep.target) { // 这个时候是 渲染watcher, depend调用会改变
        watcher.depend()
      }
      return watcher.value
    }
  }

拿到 computed[key] 对应的 computed watcher ;如果 watcher.dirtytrue 则执行 watcher.evaluate(),然后执行 watcher.depend(), 我们看看这两个方法:

// src/core/observer/watcher.js
 evaluate () {
    this.value = this.get()
    this.dirty = false
  }
 get () {
    // 在需要进行依赖收集的时候调用
    // 设置  targetStack.push(target) 和 Dep.target = watcher
    pushTarget(this)
    let value
    try {
      // 这里会触发依赖属性的读取
      value = this.getter.call(vm, vm)
    } catch (e) {
     //...
    } finally {
        // 依赖收集结束调用
        // 设置 targetStack.pop() 和 targetStack[targetStack.length - 1]
      popTarget()
    }
    return value
  }

evaluate 的执行就是通过 this.get() 计算求值;然后把 this.dirty 设置为 false。在求值过程中,由于用于计算的值也是响应式的,所以也会触发它们的 getter。前面介绍过,它们会把当前的 watcher ,这个时候 Dep.target 是 computed watcher,作为依赖收集到自己的 dep 里。这里就相当于依赖属性的 dep 里添加了 computed watcher;同时也会将自身 dep 添加到 computed watcher 中。然后往下执行:

// src/core/observer/watcher.js
  depend () {
    let i = this.deps.length
    while (i--) {
      this.deps[i].depend() // 实际调用 dep 的 depend
    }
  }
  
// src/core/observer/dep.js
  depend () {
    if (Dep.target) {
      Dep.target.addDep(this)
    }
  }

watcher.depend() 实际就是执行了上面的代码,watcher.evaluate() 执行的最后会将 Dep.target 重新设置,这里的 Dep.target 是渲染 watcherthis.deps[i] 就是 computed watcher 中的 dep ,也就是依赖属性的 dep 。所以 this.deps[i].depend() 相当于将渲染 watcher 添加到依赖属性的 dep 中。也就是说依赖属性对应的 dep 中收集了渲染 watcher  和  computed watcher 。

当计算属性的依赖属性发生改变时,就会触发 setter,从而通知 watcher 更新,调用 watcher. update 方法。

// src/core/observer/watcher.js
export default class Watcher {
  // 当computed内的响应式数据触发set后
  update () { 
    if (this.lazy) {
      // 通知computed需要重新计算了
      this.dirty = true
    } 
  }
}

首先通知 computed watcher 需要进行重新计算,然后通知到视图执行渲染,渲染中会访问到 computed 计算后的值,最后渲染到页面。

watch

// src/core/instance/state.js
function initWatch (vm: Component, watch: Object) {
  // 遍历 watch 对象
  for (const key in watch) {
    const handler = watch[key]
    if (Array.isArray(handler)) {
      //如果 handler 是数组,则遍历每一项
      for (let i = 0; i < handler.length; i++) {
        createWatcher(vm, key, handler[i])
      }
    } else {
      createWatcher(vm, key, handler)
    }
  }
}
// src/core/instance/state.js
function createWatcher (
  vm: Component,
  expOrFn: string | Function,
  handler: any,
  options?: Object
) {
  // 如果 handler 为对象,则获取其中的 handler 选项的值
  if (isPlainObject(handler)) {
    options = handler
    handler = handler.handler
  }
  // 如果 hander 为字符串,则说明是一个 methods 方法,获取 vm[handler]
  if (typeof handler === 'string') {
    handler = vm[handler]
  }
  return vm.$watch(expOrFn, handler, options)
}

首先对 handler 做判断,拿到最终的回调函数,最后返回执行 vm.$watchvm.$watch 定义在 stateMixin 中:

// src/core/instance/state.js
export function stateMixin (Vue: Class<Component>) {
   // ...
  Vue.prototype.$watch = function (
    expOrFn: string | Function,
    cb: any,
    options?: Object
  ): Function {
    const vm: Component = this
    // 处理 cb 可能是对象
    if (isPlainObject(cb)) {
      return createWatcher(vm, expOrFn, cb, options)
    }
    // options.user 表示user watcher,还有渲染 watcher,即 updateComponent 方法中实例化的 watcher
    options = options || {}
    options.user = true
    // 创建 Watcher
    const watcher = new Watcher(vm, expOrFn, cb, options)
    // 如果用户设置了 immediate 为 true,则立即执行一次回调函数
    if (options.immediate) {
      const info = `callback for immediate watcher "${watcher.expression}"`
      pushTarget()
      invokeWithErrorHandling(cb, vm, [watcher.value], vm, info)
      popTarget()
    }
    //  返回一个函数,用于移除这个 watcher
    return function unwatchFn () {
      watcher.teardown()
    }
  }
}

vm.$watch 主要做了这么几件事:

  • 处理 cb 是对象的情况。
  • 通过 options.user = true 标识 user watcher
  • 创建 Watcher 实例。
  • 如果用户设置了 immediate 为 true,则立即执行一次回调函数。
  • 返回一个函数,用于移除这个 watcher

当我们在使用 watch 设置了 deep: true 的时候,就会走得这里。

// src/core/observer/watcher.js
export default class Watcher {
  get () {
     //...
     if (this.deep) {
        traverse(value)
      }
      // ...
  }
}

还记得之前介绍过,这里会递归去访问 value,触发它所有子项的 getter ,这样就形成了深度监听。

通过对 computedwatch 属性的实现分析,computed 主要用于某个值依赖其他属性的计算而获得的应用,
watch 应用于当某个属性发生改变时我们要做一些操作。computedwatch 本质上都是同过 Watcher 实现的。
一个是 computed watcher ,另一个是 user watcher

相关链接

Vue源码解读(预):手写一个简易版Vue

Vue源码解读(一):准备工作

Vue源码解读(二):初始化和挂载

Vue源码解读(三):响应式原理

Vue源码解读(四):更新策略

Vue源码解读(五):render和VNode

Vue源码解读(六):update和patch

Vue源码解读(七):模板编译

如果觉得还凑合的话,给个赞吧!!!也可以来我的 个人博客 逛逛!

posted @ 2021-09-14 09:16  明么  阅读(183)  评论(0编辑  收藏  举报