// 创建 vm
let vm = new Vue({
data: {
a: [{}, {}, {}]
}
})
// 键路径
vm.$watch('a', function () {
// 做点什么
})
// hook 一个 console。log
let _log = console.log
console.log = function (data) {
// do someting
_log.call(this, data)
}
// 简单介绍 var a = new Object(); // 创建一个对象,没有父类 var b = Object.create(a.prototype); // b 继承了a的原型
// 获取原型
const arrayProto = Array.prototype
// 创建新原型对象
export const arrayMethods = Object.create(arrayProto)
// 给新原型实现这些函数
[
'push',
'pop',
'shift',
'unshift',
'splice',
'sort',
'reverse'
]
.forEach(function (method) {
// 获取新原型函数 (此时未实现 undefined)
const original = arrayProto[method]
// 给新原型添加函数实现
Object.defineProperty(arrayMethods, method, {
value: function mutator() {
let i = arguments.length
// 获取参数
const args = new Array(i)
while (i--) {
args[i] = arguments[i]
}
// 实现函数
const result = original.apply(this, args)
// 获取观察者
const ob = this.__ob__
// 是否更改数组本身
let inserted
switch (method) {
case 'push':
inserted = args
break
case 'unshift':
inserted = args
break
case 'splice':
inserted = args.slice(2)
break
}
// 观察新数组
inserted && ob.observeArray(inserted)
// 触发更新
ob.dep.notify()
return result
},
enumerable: true,
writable: true,
configurable: true
})
})
export function Observer (value) {
this.dep = new Dep()
this.value = value
// 如果是数组就更改其原型指向
if (Array.isArray(value)) {
value.__proto__ = arrayMethods
this.observeArray(value)
} else {
this.walk(value)
}
}
// 观测数据元素
Observer.prototype.observeArray = function (items) {
for (let i = 0, l = items.length; i < l; i++) {
observe(items[i])
}
}
Watcher.prototype.update = function (dep) {
console.log('2.update')
const value = this.get()
const oldValue = this.value
this.value = value
if (value !== this.value || value !== null) {
this.cb.call(this.vm, value, oldValue)
// 如果没有此函数, 会导致重复调用 $watch 回调函数。
// 原因:数组变异过了,并对新数组也进行了观察,应该移除旧的观察者
dep.subs.shift()
}
}
const vm = new Vue({
data: {
b: [{a: 'a'}, {b: 'b'}]
}
})
vm.$watch('b', (val) => {
console.log('------我看到你们了-----')
})
vm.b.push({c: 'c'})
vm.b.pop({c: 'c'})
vm.b.push({c: 'c'})
// 结果:
// console.log('------我看到你们了-----')
// console.log('------我看到你们了-----')
// console.log('------我看到你们了-----')
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有