1.js
class watcher{
constructor(opts){
this.$data = this.getbaseType(opts.data) === 'Object' ? opts.data: {};
this.$watch = this.getbaseType(opts.watch) === 'Object' ? opts.watch : {};
for(let key in opts.data){
this.setData(key)
}
}
getbaseType(target) {
const typeStr = Object.prototype.toString.apply(target);
return typeStr.slice(8, -1);
}
setData(_key){
Object.defineProperty(this,_key,{
get: function () {
return this.$data[_key];
},
set : function (val) {
const oldVal = this.$data[_key];
if(oldVal === val)return val;
this.$data[_key] = val;
this.$watch[_key] && typeof this.$watch[_key] === 'function' && (
this.$watch[_key].call(this,val,oldVal)
);
return val;
},
});
}
}
// export default watcher;
2.html
wathc
3. 给vm.a 从新赋值 就能看到 newVal 和oldVal的变化
总结
以上所述是小编给大家介绍的js 实现watch监听数据变化的代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!



