Vue双向数据绑定之原理及实现2
一、数据代理 我们封装的代码中,进行数据访问是 myVue.data.name ,而实际Vue中的如果要获取数据肯定不需要添加 data 选项即 myVue.name 、 myVue.skill 。 此时就可以通过代理,将data数据选项绑定在Vue对象中,修改时同步到data。 function Vue(options){ this.el = options.el // 元素 this.data = options.data // 数据 this.watcher = {} // 属性、数据、元素 的关联 var self = this Object.keys(this.data).forEach(function(key){ // 遍历所有key self.proxyKeys(key); // 添加代理(data项的处理) self.defineProperty(self.data, key, self.data[key]) }) // 解析DOM this.compile() } Vue.prototype = { proxyKeys(key){ var self = this Object.defineProperty(this, key, { enumerable: false, configurable: true, get(){ return self.data[key