对象的响应式
-
目录结构:
-
执行关系:
-
observe.js
import Observer from './Observer'
export default function observe (value) {
// 如果 value 不是对象,则不处理
if (typeof value != 'object' || !value) return
var ob
if (value.__ob__) {
ob = value.__ob__
} else {
ob = new Observer(value)
}
return ob
}
- Observer:
import { def } from './utils'
import defineReactive from './defineReactive'
import { arrayMethods } from './array'
// 将一个 Object 对象的每个层级都转换为响应式的
export default class Observer {
constructor (value) {
def (value, '__ob__', this, false)
this.walk(value)
}
}
walk (value) {
for (let key in value) {
defineReactive(value, key, value[key])
}
}
}
- defineReactive:
import observe from './observe'
export default function defineReactive (data, key, val) {
observe(val)
Object.defineProperty(data, key, {
enumerable: true,
configurable: true,
get () {
console.log(`${key} 被访问了,是 ${val}`)
return val
},
set (newVal) {
console.log(`${key} 被修改了,是 ${newVal}`)
if (newVal === val) {
return
}
val = newVal
observe(newVal)
}
})
}
- utils:
export function def (data, key, value, enumerable, writable) {
Object.defineProperty(data, key, {
value,
writable,
enumerable
})
}
- index:
import observe from './observe'
let obj = {
a: {
b: {
c: {
d: 6666
}
}
}
}
observe(obj)
obj.a.b.c.d++
-
测试效果: