仿写Vue的{{}}语法思路:
1.获取dom元素中的innerText内容,判断是否有{{}}符号
2.正则匹配{{}}内容,获取{{}}中的内容A
3.通过内容A和定义的对象data内容,去递归查找匹配内容B
4.把内容B重新赋值给dom元素innerText
以下完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{aaa.aab.aac}}</h1>
<h2>{{bbb.bbc}}</h2>
<h3>{{ccc}}</h3>
<h4>我</h4>
<script>
let data = {
aaa: { aab: { aac: '观音大士' } },
bbb: { bbc: '黑熊精' },
ccc: '红孩儿',
}
let doms = document.body.children
// 2.把处理后的文字重新赋值给dom元素
function getValue(data, str, key) {
// 3.如果data里面也是对象
if (str.includes('.')) {
const index = str.indexOf('.')
const dataChlid = data[str.substr(0, index)]
const pre = str.substr(0, index + 1)
const after = str.substr(index + 1)
getValue(dataChlid, after, key)
} else {
doms[key].innerHTML = data[str]
}
}
// 1.读取dom元素,利用正则获取dom元素中{{}}中的内容
window.justMounted = () => {
// 获取body下的children
for (const key in doms) {
// 确定不是script标签
if (doms[key].localName !== 'script') {
const text = doms[key].innerText // {{ aaa }}
// 正则匹配且存在{{}}
const regex = /\{\{([^{}]+)\}\}/;
let match = text?.match(regex)
// 如果真实DOM内容存在{{}}
if (match) {
const innerText = match[1]
// 把获取到的文字交给以下方法处理
getValue(data, innerText, key)
}
}
}
}
window.justMounted()
// 如果{{}}}报错,边界判断,
</script>
</body>
</html>
做个记录,如有不足,欢迎指正。
积跬步,至千里。感谢前进路上的每个小困难,冲!!