class Watcher {
constructor(vm, key, cb) {
// 当前vue实例
this.vm = vm
// 订阅的属性名
this.key = key
// 数据变化后要执行的函数
this.cb = cb
// 触发getter之前,要将当前订阅者实例存储在dep
Dep.target = this
// 记录下原来的值, 用于更新检测(导致了getter属性的触发)
this.oldValue = vm[key]
// 操作结束之后清除target,用于存储下一个watch实例
Dep.target = null
}
// 数据变化时,更新视图功能
update () {
const newValue = this.vm[this.key]
// 数据如果没有改变直接返回
if(newValue === this.oldValue) return
// 数据改变,调用更新回调
this.cb(newValue)
}
}
VUE响应式原理-Watch类
最新推荐文章于 2023-06-08 16:24:29 发布