[摘要]本篇文章给大家带来的内容是关于vue观察模式的简单理解,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。以下是我对vue观察者模式的理解:不要对框架的偏见, 你真的了解jquery、a...
本篇文章给大家带来的内容是关于vue观察模式的简单理解,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
以下是我对vue观察者模式的理解:
不要对框架的偏见, 你真的了解jquery、angular、react 等等,框架是什么只是工具而已。
你用过jquery的 trigger、on、off 事件绑定的方法吗?事实上 vue 不过也是这种模式,只不过vue 是自动调用on方法,自动触发trigger。甚至可以不用jquery对事件监听触发的实现。其实最终解释就是对某种事件的callback(基础原理)。
以下是源码目录截图:

1... vue 实例初始化时,会对data函数返回的对象里的属性调用以下方法,代码注释如下:
// 这个是 vue 绑定自动绑定事件的方法和触发事件方法, 会把data函数返回的对象变量属性,重写对应属性的 赋值 和获取的操作。具体查看 (mdn Object.defineProperty api)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
// watcher 对象, 如果存在
if (Dep.target) {
// 把Watcher 实例 推入 Dep 实例的 subs 数组里, 这个就相当于 on
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 实例 中subs 里数组 中所有 Watcher 实例, 然后调用Watcher实例里的 update方法(), 这个就相当于 trigger。
dep.notify()
}
})