##加深响应式原理学习
export default class MVVM {
constructor(config){
//根节点
this.$el = config.el;
this.$data = config.data;
this.methods = config.methods;
/*
虽然也可以 在里边添加, 这里可能是为了
这里的作用 不是 为了添加响应式 而是 把$data里边的所有属性(打印this 一目了然) 添加到当前类里边
所以就能够通过 访问this.xxx = this.$data.xxx
*/
Object.keys(this.$data).forEach(key => {
this.DataProxy(key);
})
this._Observe(this.$data); //this.$data 这个对象 进行代理,如果判断里边还有 对象 就 递归代理
this.list.push(11)
console.log(this);
}
// 数据代理 通过访问this.xxx = this.$data.xxx
DataProxy(key){
let that = this;
Object.defineProperty(that,key,{
configurable:false,
enumerable:true,
get(){
return this.$data[key];
},
set(val){
console.log("更新了");
this.$data[key] = val;
}
})
}
//使用proxy 代理是为了 添加响应式的 问题 好像不能代理到 深层
_Observe(data){
let handler = {
get(target,key){
let item = target[key];//保存值
if(typeof item === "object"){
return new Proxy(item,handler);
}else{
return item
}
},
set(target,key,value){
if(target[key] !== value){
target[key] = value
console.log("该更新了");
}
return true
}
}
this.$data = new Proxy(data,handler);
}
}
//使用
let app = new MVVM({
el:"#app",
data:{
text:"this is a title",
student:{
name:"nada",
obj:{
deep:1
}
},
list:[1,2,3,4]
},
methods: {
changeText(){
this.text = "this ia a panda"
}
},
})
- 这里的DataProxy 方法,不是 为了添加响应式 而是 把 d a t a 里 边 的 所 有 属 性 添 加 到 当 前 类 里 边 ( 打 印 t h i s 一 目 了 然 ) , 达 到 访 问 t h i s . x x x = t h i s . data里边的所有属性 添加到当前类里边 (打印this 一目了然),达到访问this.xxx = this. data里边的所有属性添加到当前类里边(打印this一目了然),达到访问this.xxx=this.data.xxx
学工网 工具方法
let el = document.querySelectorAll("el-table-column");
let res = [...el].map(item => {
let obj = {}
if(!(item.getAttribute("min-width")) && item.getAttribute("width")){
obj = {
prop:item.getAttribute("prop"),
label:item.getAttribute("label"),
width:item.getAttribute("width"),
showOverflowTooltip: true
}
$(item).children("template")[0] !== undefined && (obj = {...obj,needTamplate:true});
if(item.getAttribute("label") == "操作"){
obj = {
...obj,
prop:"doSomething",
fixed:item.getAttribute("fixed")
}
delete obj.showOverflowTooltip
}
return obj
}else if(!(item.getAttribute("width")) && item.getAttribute("min-width")){
obj = {
prop:item.getAttribute("prop"),
label:item.getAttribute("label"),
minWidth:item.getAttribute("min-width"),
showOverflowTooltip: true
}
$(item).children("template")[0] !== undefined && (obj = {...obj,needTamplate:true});
if(item.getAttribute("label") == "操作"){
obj = {
...obj,
prop:"doSomething",
fixed:item.getAttribute("fixed")
}
delete obj.showOverflowTooltip
}
return obj
}
})
个人总结
- 响应式 可以通过Object.defineProperty()或Proxy()代理来实现
- dep类 和 watcher类 感觉是通过发布订阅模式 来 实现派发 更新节点 的(现阶段无法看懂)