前文
我一直有一个疑问,就是vue的源码defineRective部分的childob.dep.depend这行代码到底有什么作用
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()
}
})
}
childob.dep.depend其主要目的就是在数组以及对象进行Vue.set的时候进行触发响应
那设置成获取属性的时候dep直接响应难道不可以么?
比如在获取childOb的时候
let childOb = !shallow && observe(val, dep)
将definedproperty的时候的闭包dep传入
这样就不需要再运行childOb.dep.depend收集依赖了
根据我个人的测试
认为这行代码更像是一种设计思想,在将源码修改成获取属性的封闭dep之后单测依然可以正常通过
HeadlessChrome 78.0.3882 (Windows 10.0.0): Executed 1248 of 1248 (1 FAILED) (15.102 secs / 14.846 secs)
TOTAL: 1 FAILED, 1247 SUCCESS
唯一的一个失败是
HeadlessChrome 78.0.3882 (Windows 10.0.0) Observer observing object prop change FAILED
Expected 2 to be 3.
at UserContext.<anonymous> (webpack:///test/unit/modules/observer/observer.spec.js:195:32 <- index.js:61131:33)
Expected 2 to be 3.
at UserContext.<anonymous> (webpack:///test/unit/modules/observer/observer.spec.js:200:41 <- index.js:61139:42)
Expected 3 to be 4.
at UserContext.<anonymous> (webpack:///test/unit/modules/observer/observer.spec.js:207:32 <- index.js:61145:33)
检测代码如下
expect(watcher.deps.length).toBe(3) // obj.a + a + a.b
obj.a.b = 3
expect(watcher.update.calls.count()).toBe(1)
// swap object
obj.a = { b: 4 }
expect(watcher.update.calls.count()).toBe(3)
watcher.deps = []
Dep.target = watcher
obj.a.b
obj.c
Dep.target = null
expect(watcher.deps.length).toBe(4)
这个我认为是完全不影响的
所以我更倾向于childob.dep.depend是一种设计思想,将其改为子继承父dep属性也算是完全可以实现的。