圈里的人都知道,我们的vue 3.0面世了,以下是一个基于 proxy 实现的响应式原理
/* Vue 3.0 响应式原理*/
function Vue(){
this.$data = {a:1}
this.el = document.getElementById('app')
this.ast = '';
this.observe(this.$data);
this.render();
}
Vue.prototype.observe = function(){
var self = this;
this.$data = new Proxy(this.$data,{
set:function(target,key,newValue){
target[key] = newValue;
self.render()
},
get:function(target,key){
return target[key];
}
})
}
Vue.prototype.render = function(){
this.ast = 'i am ' + this.$data.a;
this.el.innerHTML = this.ast;
}
调用时这样写:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src='./vue.js'></script>
<title>Document</title>
</head>
<body>
<div id='app'></div>
<script>
new Vue();
</script>
</body>
</html>
呃,是不是没什么返映,在控制台里这么写看看
new Vue().$a = 99;