Vued的两大特征:数据驱动 & 组件化开发
Vue2.0响应式原理:发布订阅模式 + 双向数据绑定
<div id="app">
<div>View-1:<span class="view1">11111</span></div>
<div>View-2:<span class="view2">22222</span></div>
</div>
let Dep = {
clientList: {},
listen: function(key,fn) {
(this.clientList[key] || (this.clientList[key]=[])).push(fn);
},
trigger: function() {
let key = Array.prototype.shift.call(arguments);
let fns = this.clientList[key];
if(!fns || fns.length===0) {
return false;
}
for(let i=0,fn; fn=fns[i++];) {
fn.apply(this,arguments);
}
}
}
let dataHi = function({data,tag,datakey,selector}) {
let ele = document.querySelectorAll(selector)[0];
Object.defineProperty(data,datakey,{
get: function() {
console.log('get',val);
return val;
},
set: function(newVal) {
console.log('set',newVal);
val = newVal;
Dep.trigger(tag,val)
}
});
Dep.listen(tag,function(text) {
ele.innerHTML = text;
});
}
let textObj = {};
dataHi({
data: textObj,
tag: "view-1",
datakey: "one",
selector: ".view1",
});
dataHi({
data: textObj,
tag: "view-2",
datakey: "two",
selector: ".view2",
});
textObj.one = "one-one-one";
textObj.two = "two-two-two";
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8f3af03e8c74727012912ba29ae82e37.png)
Vue2.0响应式原理:proxy() 代理
let obj = {
name: "jason",
age: 22,
}
const pro = new Proxy(obj,{
get(target,pName) {
console.log("读取: ",pName);
return target[pName];
},
set(target,pName,val) {
console.log("修改: ",pName,val);
target[pName] = val;
},
deleteProperty(target,pName) {
console.log("删除: ",pName);
return delete target[pName];
}
});
pro.name
pro.name = "Code"
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/378c79becc9bd862f14ebcfa39da42b2.png)