Vue2实现响应式核心就是Object.defineProperty数据劫持,针对数组重写了数组方法
在Vue2源码中实现响应式考虑到更多情况,以下所写了V2实现响应式的核心逻辑
const data = {
name: 'wft',
age: 18,
info: {
test: '哈哈哈'
},
list: [1, 2, 3, 4, 5]
}
const oldArrProto = Array.prototype;
const newArrProto = Object.create(oldArrProto);
['push', 'pop', 'shift', 'unshift', 'splice'].forEach(methodName => {
newArrProto[methodName] = function () { // 1. 更新视图; 2. 执行原来的方法
oldArrProto[methodName].call(this, ...arguments)
console.log('更新视图操作----->>>')
}
})
observer(data)
function observer(target) {
if (typeof target !== 'object' || target === null) {
return target
}
if (target.constructor === Array) { // 如果是数组的话, 就把原型对象修改成重写之后的(主要是为了能够进行更新视图操作)
target.__proto__ = new