Vue的一个最大的特点就是数据响应式,修改数据之后即会更新视图,这样我们只需要聚焦在数据上,不必过多关注怎么取修改视图。Vue的数据响应主要是通过ES5中的Object.defineProperty()来实现的,具体怎么实现的,让我们从源码的角度分析。
首先,在初始化的过程中,Vue就会为data和props里的属性加上响应式。在new Vue的过程中会执行initState(vm)函数,该函数在'core/instance/state.js'中被定义
可以看到该函数的主要功能是初始化props,methods, data, computed等等。这里我们先关注
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中,主要完成的是拿到vm实例中的props,然后对props进行校验。同时使用defineReactive()函数对props中的值实现响应式。并在最后使用代理proxy将this.vm.xxx代理到this.xxx,方便用户访问。
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) }
在initData中,首先是对data进行一些判断,然后是比较data中的属性跟props和methods中的名字是否有相同的,有的话就抛出警告。最后同样使用proxy函数对data进行代理,使得使用this.xxx能够访问到props中的属性,最后使用observe函数观察data中的数据。
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 */) }
observe函数定义在'core/observer/index.js'中,主要完成的功能是对于传进来的value值,首先判断是不是对象或者是不是VNode的实例,如果不是对象或者是VNode的实例,则直接返回。
然后判断该对象有没有'__ob__'属性以及该属性是不是Oberserver类的实例,是的话赋值给ob,最后返回ob。否则value是不是数组,或者是不是对象,以及value是不是可扩展。是的话就创建一个Observer类。
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 }
Observer类完成了什么功能。在构造函数中,对属性进行初始化,然后使用def函数将this(也即是ob对象)定义到value(也即是data对象)中,这里为什么要用def函数而不直接用value['__ob__'] = this呢?原因应该是__ob__不是一个响应式的,所以在下面的walk函数中不用在value的属性中进行遍历,所以设置它的emurable为false(!!undefined)。
然后判断vaule对象是不是数组,是的话调用observeArray函数,不是的话调用walk函数。
在walk函数中,主要完成的功能是对对象中的每个属性调用defineReactive函数实现响应式。
在observeArray函数中,主要是对数组中的每个值调用observe函数,因为数组中可能还会有数组。
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) { for (let i = 0, l = items.length; i < l; i++) { observe(items[i]) } } }
export function def (obj: Object, key: string, val: any, enumerable?: boolean) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }) }
最后看看defineReactive函数中完成了什么功能。首先拿到该属性的描述符,判断该属性的configurable是不是false,如果是的话直接返回。
然后得到属性描述符中的getter和setter,如果传入的参数只有两个,则把该属性对应的值赋给val。并对val调用observe函数进行递归地观察。同时设置属性的get和set,它们主要完成了依赖的收集和派发更新。具体内容之后再分析。
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() } }) }
总结
在对props和data进行响应式处理时,主要是对属性调用defineReactive函数。
对于data,则会先调用observe函数,判断data中是否已经对属性进行了响应式处理,添加了__ob__属性,没有的话,则实例化Observer类。在该类中,会对__ob__属性进行挂载。同时也会判断属性值的类型,如果是数组的话,则会仔调用obeserve函数,实现对每一个值的监听。如果不是的话,则直接调用defineReactive函数。
在defindeReactive函数中,还会对属性值调用observe函数。为什么呢?想象一下,一开始,直接对data调用observe函数,但是data是一个对象,并不是数组。所以会直接调用defineReactive函数,但是data对象中可能会有数组,会有对象,所以在defineReactive中还会再调用observe函数对每个属性进行响应式初始化处理。