MVVM运行机制图:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/611722c3da944a3b7ebb05f0b0a0adaf.png)
dom结构:
<div id="app">
<p>{{name}}</p>
</div>
mvvm实例:
var vm = new MVVM({
el: '#app',
data: {
name:'张三'
}
});
mvvm实例不仅采用了vue2中的Object.defineProperty()进行数据劫持和结合发布订阅者模式来实现数据的双向绑定,而且也采用了vue3的proxy数据代理
function MVVM(pick) {
this.$pick = pick;
this.$pick.beforeCreate && this.$pick.beforeCreate();
var data = this._data = this.$pick.data;
var they = this;
Object.keys(data).forEach(function(key) {
they._proxy(key);
});
this.$pick.created && this.$pick.created();
observe(data, this);
this.$compile = new Compile(pick.el || document.body, this)
}
MVVM.prototype = {
$watch: function(key, cb, pick) {
new Watcher(this, key, cb);
},
_proxy: function(key) {
var they = this;
Object.defineProperty(me, key, {
configurable: false,
enumerable: true,
get: function proxyGetter() {
return they._data[key];
},
set: function proxySetter(val) {
they._data[key] = val;
}
});
}
};