初识
<div id="app">
<p>{{name}}</p>
<p l-text="name"></p>
<p>{{age}}</p>
<p>{{doubleAge}}</p>
<input type="text" l-model="name" />
<button @click="changeName">嘿嘿</button>
<div l-html="html"></div>
</div>
<script>
const app = new Lz({
el:'#app',
data:{
name: '栗子'
}
});
</script>
编译
class Lz{
constructor(options){
this.$options = options;
this.$data = options.data;
this.$el = options.el;
new Compile(this.$el, this);
}
}
class Compile{
constructor(el , vm){
this.$el = document.querySelector(el);
this.$vm = vm;
if(this.$el){
this.$fragment = this.node2Fragment(this.$el);
this.compile(this.$fragment);
this.$el.appendChild(this.$fragment);
}
}
node2Fragment(el){
const frag = document.createDocumentFragment();
let child;
while(child = el.firstChild){
frag.appendChild(child);
}
return frag
}
}
compile函数的实现
compile(el) {
const childNodes = el.childNodes;
Array.from(childNodes).forEach(node => {
if (this.isElement(node)) {
const nodeAttrs = node.attributes;
Array.from(nodeAttrs).forEach(attr => {
const attrName = attr.name;
const exp = attr.value;
if (this.isDirective(attrName)) {
const dir = attrName.substring(2);
this[dir] && this[dir](node, this.$vm, exp);
}
if (this.isEvent(attrName)) {
}
})
} else if (this.isInterpolation(node)) {
this.compileText(node);
}
if (node.childNodes && node.childNodes.length > 0) {
this.compile(node);
}
})
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/e5c4e9283d4710e3064185d8ca0525cb.png)