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";

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"
