原理分析
通过遍历数据, 为数据创建一个发布器Dep,并修改数据的 get 和 set ,在set中利用发布器Dep,通知订阅者Watcher进行数据更新(实际为调用Watcher 的函数)
代码
class Vue {
constructor(options) {
if (typeof options !== 'object') {
console.error('options is not a object')
return
}
if (!'el' in options || !'data' in options) {
console.error('options do not contain el and data')
}
this.el = typeof options.el == 'string' ? options.el : 'body'
let tempData = options.data
this.data = {}
//数据劫持
for(let key in tempData){
let temp = tempData[key]
const dep = new Dep(key) //创建发布器
Object.defineProperty(this.data, key, {
enumerable: true,
configurable: true,