vue源码之旅-2 - 数据响应式原理的实现

在官方文档的深入响应式原理这一节可以看到,Vue是通过Object.defineProperty 来定义数据的响应式的, 接着从源码层面来喵一眼到底是怎么做的?

src/core/instance/state.js

我简单注视了一下源码

/**
 * 1. 调用initData()方法, 初始化用户传入的 data 
 * @param {*} vm 
 */
function initData (vm: Component) {
  let data = vm.$options.data // 拿到用户传入的数据
  data = vm._data = typeof data === 'function'
    ? getData(data, vm)
    : data || {}
  if (!isPlainObject(data)) {
    data = {}
    process.env.NODE_ENV !== 'production' && warn(
      'data functions should return an object:\n' +
      'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
      vm
    )
  }
  // proxy data on instance
  // 将所有的key 取出来 存到数组里
  // Object.keys() 会把一个对象中的所有的key 取出来,返回一个由这些key组成的数组
  const keys = Object.keys(data)
  const props = vm.$options.props
  const methods = vm.$options.methods
  let i = keys.length
  while (i--) {
    const key = keys[i]
    if (process.env.NODE_ENV !== 'production') {
      if (methods && hasOwn(methods, key)) {
        warn(
          `Method "${key}" has already been defined as a data property.`,
          vm
        )
      }
    }
    if (props && hasOwn(props, key)) {
      process.env.NODE_ENV !== 'production' && warn(
        `The data property "${key}" is already declared as a prop. ` +
        `Use prop default value instead.`,
        vm
      )
    } else if (!isReserved(key)) {
      proxy(vm, `_data`, key)
    }
  }
  // observe data
  /**
   * 2. 就是对数据 进行观测
   */
  observe(data, true /* asRootData */)
}

接着看这个 observe() 方法

src/core/observer/index.js

这段代码注视的 很清楚, 就是尝试为值创建观察者实例,
主要看这句, new Observer(value) , 把要被观测的数据 传入了这个Observer类

/**
 * Attempt to create an observer instance for a value,
 * returns the new observer if successfully observed,
 * or the existing observer if the value already has one.
 */

export function observe (value: any, asRootData: ?boolean): Observer | void {
  if (!isObject(value) || value instanceof VNode) {
    return
  }
  let ob: Observer | void
  if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
    ob = value.__ob__
  } else if (
    shouldObserve &&
    !isServerRendering() &&
    (Array.isArray(value) || isPlainObject(value)) &&
    Object.isExtensible(value) &&
    !value._isVue
  ) {
    ob = new Observer(value)
  }
  if (asRootData && ob) {
    ob.vmCount++
  }
  return ob
}

接着看 Oberver 这个类
src/core/observer/index.js

export class Observer {
  value: any;
  dep: Dep;
  vmCount: number; // number of vms that have this object as root $data
  constructor (value: any) {
    this.value = value
    this.dep = new Dep()
    this.vmCount = 0
    def(value, '__ob__', this)
    if (Array.isArray(value)) {
      if (hasProto) {
        protoAugment(value, arrayMethods)
      } else {
        copyAugment(value, arrayMethods, arrayKeys)
      }
      this.observeArray(value)
    } else {
      this.walk(value)
    }
  }

  /**
   * Walk through all properties and convert them into
   * getter/setters. This method should only be called when
   * value type is Object.
   */
  walk (obj: Object) {
    const keys = Object.keys(obj)
    for (let i = 0; i < keys.length; i++) {
      defineReactive(obj, keys[i])
    }
  }

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

这个类主要是先对观测的数据 做了一个判断,

  1. 如果是对象, 就走 this.walk(value) 这个方法

那么接着看 this.walk() 方法, 这个方法就是先把所有的 key 放到一个数组里, 然后便利所有的key,调用 defineReactive(), 在这个方法里, 我们看到了 一个重要的方法Object.defineProperty(), 这个方法就是给所有的key 重新定义响应式,同时给每个key 都加上setter 和 getter, 同时在set数据的时候呢, 还会调用 dep.notify() 更新方法


/**
 * Define a reactive property on an Object.
 */
export function defineReactive (
  obj: Object,
  key: string,
  val: any,
  customSetter?: ?Function,
  shallow?: boolean
) {
  const dep = new Dep()

  const property = Object.getOwnPropertyDescriptor(obj, key)
  if (property && property.configurable === false) {
    return
  }

  // cater for pre-defined getter/setters
  const getter = property && property.get
  const setter = property && property.set

  let childOb = !shallow && observe(val)
  Object.defineProperty(obj, key, {
    enumerable: true,
    configurable: true,
    get: function reactiveGetter () {
      const value = getter ? getter.call(obj) : val
      if (Dep.target) {
        dep.depend()
        if (childOb) {
          childOb.dep.depend()
          if (Array.isArray(value)) {
            dependArray(value)
          }
        }
      }
      return value
    },
    set: function reactiveSetter (newVal) {
      const value = getter ? getter.call(obj) : val
      /* eslint-disable no-self-compare */
      if (newVal === value || (newVal !== newVal && value !== value)) {
        return
      }
      /* eslint-enable no-self-compare */
      if (process.env.NODE_ENV !== 'production' && customSetter) {
        customSetter()
      }
      if (setter) {
        setter.call(obj, newVal)
      } else {
        val = newVal
      }
      childOb = !shallow && observe(newVal)
      dep.notify()
    }
  })
}

以上是vue 对 对象的 响应式处理, 那么是怎么处理数组类型的数据的呢,

  1. 如果是数组,就是先拷贝数组原型的方法,进行重写, 然后调用def 方法,最后通知更新

src/core/observer/array.js

扫描二维码关注公众号,回复: 10259606 查看本文章
/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */

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

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

/**
 * Intercept mutating methods and emit events
 */
[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]
.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]
  def(arrayMethods, method, function mutator (...args) {
    const result = original.apply(this, args)
    const ob = this.__ob__
    let inserted
    switch (method) {
      case 'push':
      case 'unshift':
        inserted = args
        break
      case 'splice':
        inserted = args.slice(2)
        break
    }
    if (inserted) ob.observeArray(inserted)
    // notify change
    ob.dep.notify()
    return result
  })
})

总结:

  1. 先调用 initData() 方法, 初始化用户传入的data,然后对这些数据 进行 观测, 也就是new Oberser()
  2. 接着 会判断这个数据类型是对象,还是数组, 如果是对象就便利所有的key , 调用 defineReactive() 方法,重新定义数据, 添加响应式, 给个key 都添加setter 和 getter,多层结构时进行递归
  3. 如果是数组, 就拷贝数组原型上的方法,然后进行重写数组的方法,接着调用def() 方法,进行switch…case 判断, 最后通知更新
发布了63 篇原创文章 · 获赞 100 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/qq_36407748/article/details/105139385