Vue解析总纲
上一节:防Vue系列-02:代码改成Vue的形式
怎么将解析data.xxx.xxx
<div id="root">
<p>{{ name.firstName }}</p>
</div>
const vm = new Vue({
el: "#root",
data: {
name: {
firstName:'小',
firstName:'陈',
},
},
});
- 如何解析{{name.firstName }}
//解析data.xxx.xx
/**
*@params obj:Object data:{nama:{firstName:'小',lastName:'陈'}}
*@params path:String 'xxx.xxx'
*/
function getValueByPath(data, path) {
let paths = path.split("."); [name,firstName]
let res = data;
//循环查找
for (let index = 0; index < paths.length; index++) {
res = res[paths[index]];
}
// res === '小'
return res;
}
- 然后在之前的compiler 解析函数中添加将getValueByPath做成数据过滤
//正则,用来匹配{{}}
let r = /\{\{(.+?)\}\}/g;
/**
*@params template:DOM
*@params data:Object
*/
function compiler(template, data) {
let childNodes = template.childNodes; //取出root下的子节点
// 遍历子节点
for (let index = 0; index < childNodes.length; index++) {
let type = childNodes[index].nodeType; //获取子节点的类型
//type === 3 文本节点
if (type === 3) {
//文本节点 判断 是否有{{}}
let txt = childNodes[index].nodeValue; //只有文本节点才有
text = txt.replace(r, (_, g) => {
//======== 修改区域start =====
let key = getValueByPath(data,g.trim()); //两边去空格 key = 'name'
return key; // data[key] ===》key
//======== 修改区域end =====
});
//文本赋值
childNodes[index].nodeValue = text;
}
//type === 1 元素节点
else if (type === 1) {
//如果是元素,要判断其子节点是否要插值,递归
compiler(childNodes[index], data);
}
}
}