<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<!-- 写模板 -->
<div id="app">
<div>
<p>{{name}}</p>
<p>{{age}}</p>
</div>
<div>
<p>{{name}}</p>
</div>
</div>
</body>
<script>
// 1. 拿到模板
let rzz = /\{\{(.+?)\}\}/g;
//递归
function recursionDOM(temple, data) {
let $childNodes = temple.childNodes;
let $data = data;
for (let i = 0; i < $childNodes.length; i++) {
if ($childNodes[i].nodeType === 3) {
// 文本节点, 可以判断里面是否有 {{}} 插值
let txt = $childNodes[i].nodeValue;
txt = txt.replace(rzz, (_, g) => {
let key = g.trim();
return data[key];
});
$childNodes[i].nodeValue = txt;
} else if ($childNodes[i].nodeType === 1) {
recursionDOM($childNodes[i], $data);
}
}
}
function LZVue(option) {
//先将数据复制过来
this._data = option.data;
this._el = option.el;
this._templeDOM = document.querySelector(this._el);
this._parentNode = this._templeDOM.parentNode;
// 渲染工作
this.render()
}
LZVue.prototype.render = function () {
this.recursionDOM();
}
LZVue.prototype.recursionDOM = function () {
let realDOMtree = this._templeDOM.cloneNode(true)
recursionDOM(realDOMtree, this._data);
this.update(realDOMtree)
}
/** 将 DOM 的元素 放到页面中 */
LZVue.prototype.update = function (real) {
this._parentNode.replaceChild(real, document.querySelector('#app'));
}
let app = new LZVue({
data: {
name: "张山",
age: "15"
},
el: "#app"
});
</script>
</html>