How to convert data with { {}} real dom into dom with data
- How to replace { {name}} in the p tag with Xiao Chen
<div id="root">
<p>{
{
name}}</p>
</div>
- Curious? Then start the dom operation
1.首先拿到模板,获取dom对象,这里尽量模仿vue中的做法
let templateTest = document.querySelector("#root");
2.准备好要填充的对象 data.XXX
let data = {
name: "小陈"
};
- What is the use of root dom? Use the compiler function to traverse each child node
in the dom. Use regular expressions to match in the text node. { {}} If you don’t understand the regularity, please learn the regularity first
//正则,用来匹配{
{}}
let r = /\{\{(.+?)\}\}/g;
3.data与模板结合难点!!!! 正则,递归,js原生语法
在Vue源码中是 字符串 DOM===>字符串模板===>虚拟DOM===>真正的DOM
/**
*@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) => {
let key = g.trim(); //两边去空格 key = 'name'
return data[key];
});
//文本赋值
childNodes[index].nodeValue = text;
}
//type === 1 元素节点
else if (type === 1) {
//如果是元素,要判断其子节点是否要插值,递归
compiler(childNodes[index], data);
}
}
}
- According to the above code, a rootDOM with data can be obtained. The next step is
to replace the DOM with data-. -
let generateNode = templateTest.cloneNode(true); //克隆原来的dom节点
console.log(templateTest);//带{
{}}dom
compiler(generateNode, data);
console.log(generateNode);//替换成数据dom
//获取root父节点替换成数据dom
root.parentNode.replaceChild(generateNode, root);
Summary: Although this can simply replace text, there are still many problems. It can only be static, and { {obj.xxx }} cannot be implemented either.