两个文件,一个html文件,一个js文件。
<body>
<div id="app">
<h1>{{str}}</h1>
{{str}}11
</div>
</body>
<script src="./Vue.js"></script>
<script>
new Vue({
el: '#app',
data: {
str: "你好"
}
})
</script>
class Vue {
constructor(options) {
this.$el = document.querySelector(options.el);
this.$data = options.data;
this.compile(this.$el);
}
// 编译模板
compile(node) {
node.childNodes.forEach((item, index) => {
console.log(item, item.nodeType)
// 判断节点类型
// 1===元素节点
if (item.nodeType === 1) { }
// 2===属性节点
else if (item.nodeType === 2) { }
// 3===文本节点
else if (item.nodeType === 3) {
let reg = /\{\{(.*?)\}\}/g;
let text = item.textContent;
item.textContent = text.replace(reg, (match, key) => {
key = key.trim();
return this.$data[key];
})
}
})
}
}