关于javascript:Vue源码解读三响应式原理

2次阅读

共计 31264 个字符,预计需要花费 79 分钟才能阅读完成。

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 源码解读(七):模板编译(待续)]()

如果感觉还对付的话,给个赞吧!!!也能够来我的集体博客逛逛 https://www.mingme.net/

正文完
 0