文章目录
面试被问到《介绍一下Vue的响应式原理》如何回答
Vue初始化时会调用initData()方法,方法内部会调用observe()方法对数据进行观测,observe()方法先判断data是否为对象,如果不是对象不进行观测。再判断是否已经被观测,没有被观测的话会new 一个Observer去观测对象。观测时又分为两种,对象的观测和数组的观测。
如果观测的是对象
就会调用walk()方法,walk()方法会遍历所有对象并调用defineReactive方法,defineReactive方法会判断如果观测的值还是一个对象,会重新调用observe方法进行递归观测,然后使用object.definedProperty方法给属性添加get/set方法给属性定义响应式,如果数据被获取时,就会调用get方法,如果get方法被调用,就会收集点前的watcher,如果数据发生变化,就会调用set方法,判断数据是否和元数据一致,如果不一致就会调用notify方法就会通知视图更新。
如果观测的是数组
就会调用protoAugment将原型链指向我们新定义的方法,当我们调用这些方法时,方法内部还是会调用原有的方法,但是会在最后会手动通知视图更新。操作个别的可能会新增数组的方法时,如果有新增的数据就会调用observeArray方法对数据进行观测,因为新增的数据也可能是对象,原理和对象相同。
Vue初始化会调用initData()方法
vue/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) --------------------调用initData()方法
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
initData()方法会调用observe()方法对数据进行观测
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()
/**
* 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) {
判断data是否为对象,如果不是对象不进行观测
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类
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.
*/
遍历所有属性并将它们转换为getter/setter。
这个方法应该只在x值类型为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.
*/
观察Array项的列表
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
}
defineReactive方法
/**
* 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
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()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify()
}
})
}
protoAugment方法
/**
* Augment a target Object or Array by intercepting
* the prototype chain using __proto__
*/
通过拦截增加目标对象或数组使用__proto__的原型链
function protoAugment (target, src: Object) {
/* eslint-disable no-proto */
target.__proto__ = src
/* eslint-enable no-proto */
}
arrayMethods
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
const methodsToPatch = [
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
/**
* Intercept mutating methods and emit events
*/
methodsToPatch.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
})
})