//模拟数据更新之后的操作
function cb (val) {
/* 渲染视图 */
console.log("视图更新啦~");
}
使用了Object.defineReactive的方法:mdn
function defineReactive (obj, key, val) {
Object.defineProperty(obj, key, {
enumerable: true, /* 属性可枚举 */
configurable: true, /* 属性可被修改或删除 */
get: function reactiveGetter () {
return val; /* 实际上会依赖收集,下一小节会讲 */
},
set: function reactiveSetter (newVal) {
if (newVal === val) return;
cb(newVal);
}
});
}
将目标对象所有属性进行监听
function observer (value) {
if (!value || (typeof value !== 'object')) {
return;
}
Object.keys(value).forEach((key) => {
defineReactive(value, key, value[key]);
});
}
/*
class Test{
constructor(options){
console.log(options)//options为new的时候传入的参数
}
}
a=new Test({
data:{test:'我是你爹'},
watch:{userid:function(){}},
created:function(){
console.log('created')
}
})
{data: {…}, watch: {…}, created: ƒ}
*/
class Vue {
/* Vue构造类 */
constructor(options) {
this._data = options.data;
observer(this._data);
}
}
let o = new Vue({
data: {
test: "I am test."
}
});
o._data.test = "hello,world."; /* 视图更新啦~ */