This article brings you a simple understanding of the vue observation mode. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The following is my understanding of the vue observer pattern:
Don’t be biased against the framework, you really understand jquery, Angular, react, etc., frameworks are just tools.
Have you ever used jquery’s trigger, on, off event binding methods? In fact, vue is also in this mode, except that vue automatically calls the on method and automatically triggers the trigger. You can even implement event listening and triggering without jquery. In fact, the final explanation is the callback (basic principle) of a certain event.
The following is a screenshot of the source code directory:
1... When the vue instance is initialized, it will be in the object returned by the data function. The following method is called for the attribute of , run the method represented by exporFn. This method basically includes calling the getter method in 1...
(Think about the operations in the render hook, which basically include getting the value in the vue instance attribute data or getting the value of the computed attribute of the vue instance). // 这个是 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()
}
})
The above is the detailed content of A simple understanding of vue observation mode. For more information, please follow other related articles on the PHP Chinese website!