代码详解Vuejs响应式原理

2020-06-16 06:06:40易采站长站整理

this._data = options.data;
observer(this._data, options.render) /*把所有数据变成可观察的*/
}
}
let app = new Vue({
el: '#app',
data: {
text: 'text',
text2: 'text2'
},
render(){
console.log("render");
}
})

残留问题 > 上述实现只有通过app._data_text才会触发set,那么怎样才能做到app.text就能触发set呢
代理

> 通过在this对象中添加访问器属性即可实现代理,然后就可以用app.text来代替app._data.text了


_proxy(options.data);/*构造函数中*/

/*代理*/
function _proxy (data) {
const that = this;
Object.keys(data).forEach(key => {
Object.defineProperty(that, key, {
configurable: true,
enumerable: true,
get: function proxyGetter () {
return that._data[key];
},
set: function proxySetter (val) {
that._data[key] = val;
}
})
});
}

以上就是本次文章的全部内容,大家如果还有任何不明白的地方可以在下方的留言区讨论。