1、实现comile类,用与编译html模板
class Compile {
constructor(el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
if (this.$el) {
this.$fragment = this.node2Fragment(this.$el)
// 编译模板内容,同时进行依赖收集
this.compile(this.$fragment)
this.$el.appendChild(this.$fragment)
}
}
node2Fragment(el) {
const fragment = document.createDocumentFragment()
let child
while (child = el.firstChild) {
fragment.appendChild(child)
}
return fragment
}
compile(el) {
const childNodes = el.childNodes
Array.from(childNodes).forEach(node => {
// 判断节点类型
if (node.nodeType === 1) {
// element节点
console.log('编译元素节点:' + node.nodeName)
}
else if (this.isInterpolation(node)) {
// 插值表达式
console.log('编译插值文本:' + node.textContent)
}
// 递归子节点
if (node.childNodes && node.childNodes.length > 0) {
this.compile(node)
}
})
}
isInterpolation(node) {
// 是文本且符合{{}}
return node.nodeType === 3 && /\{\{(.*)\}\}/ // 只兼容无空格{{name}}
}
}
测试一下
2、我下来实现一下compileText()方法,用于编译文本节点
compileText(node){
node.textContent = this.$vm[RegExp.$1]
}
调用compileText
测试
已经{{massage}}已经被替换了为真实文本了
源码地址
https://github.com/hxlTeam/hvue.git