真实 DOM 中的模板数据替换
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="root">
<div>111{{name.firstName}}-{{age}}</div>
<p>
<span>{{name.lastName}}</span>
</p>
</div>
<script>
function getValueByKey(obj, str) {
const arr = str.split('.')
let prop = null
while ((prop = arr.shift())) {
obj = obj[prop]
}
return obj
}
const reg = /\{\{(.+?)\}\}/g
function compiler(template, data) {
const childNodes = template.childNodes || []
for (let i = 0; i < childNodes.length; i++) {
const nodeType = childNodes[i].nodeType
if (nodeType === 1) {
compiler(childNodes[i], data)
} else if (nodeType === 3) {
const txt = childNodes[i].nodeValue
const value = txt.replace(reg, function (_, g) {
const key = g.trim()
return getValueByKey(data, key)
})
childNodes[i].nodeValue = value
}
}
}
function OVue(obj) {
this._el = obj.el
this._data = obj.data
this._template = document.querySelector(this._el)
this._parent = this._template.parentNode
this.render()
}
OVue.prototype.render = function () {
this.compiler()
}
OVue.prototype.compiler = function () {
const tmpRootCln = this._template.cloneNode(true)
compiler(tmpRootCln, this._data)
this.update(tmpRootCln)
}
OVue.prototype.update = function (tmpRootCln) {
this._parent.replaceChild(tmpRootCln, this._template)
}
new OVue({
el: '#root',
data: {
name: { firstName: 'wang', lastName: 'wu' },
age: 18
}
})
</script>
</body>
</html>