// 创建 vm
let vm = new Vue({
data: 'a'
})
// 键路径
vm.$watch('a.b.c', function () {
// 做点什么
})
export function observe (val) {
if (!val || typeof val !== 'object') {
return
}
return new Observer(val)
}
function defineReactive (obj, key, val) {
var dep = new Dep()
var property = Object.getOwnPropertyDescriptor(obj, key)
// 是否允许修改
if (property && property.configurable === false) {
return
}
// 获取定义好的 get set 函数
var getter = property && property.get
var setter = property && property.set
var childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: () => {
var value = getter ? getter.call(obj) : val
// 说明是 Watcher 初始化时获取的, 就添加订阅者
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
}
// if isArray do some....
}
return value
},
set: (newVal) => {
var value = getter ? getter.call(obj) : val
if (value === newVal) {
return
}
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = observe(newVal)
dep.notify()
}
})
}
export default function Dep () {
this.subs = []
}
// 就是你!!~
Dep.target = null
// 添加订阅者
Dep.prototype.addSub = function (sub) {
this.subs.push(sub)
}
// 添加依赖
Dep.prototype.depend = function () {
Dep.target.addDep(this)
}
// 通知订阅者:要更新啦~
Dep.prototype.notify = function () {
this.subs.forEach(sub => sub.update())
}
export default function Watcher (vm, expOrFn, cb) {
this.cb = cb
this.vm = vm
this.expOrFn = expOrFn
this.value = this.get()
}
Watcher.prototype.get = function () {
Dep.target = this
const value = this.vm._data[this.expOrFn]
// 此时 target 有值,此时执行到了上面的 defineReactive 函数中 get 函数。就添加订阅者
Dep.target = null
// 为了不重复添加 就设置为 null
return value
}
// Vue 实例
export default function Vue(options) {
this.$options = options
this._initState()
}
// 初始化State
Vue.prototype._initState = function () {
let data = this._data = this.$options.data
Object.keys(data).forEach(key => this._proxy(key))
observe(data, this)
}
// $watch 函数,
Vue.prototype.$watch = function (expOrFn, fn, options) {
new Watcher(this, expOrFn, fn)
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有