概述
上篇文章我们已经介绍了Vue的响应式原理,并实现了对数据的监听,监听的目的是为了及时更新视图,所以这篇文章就来介绍下vue解析指令并初始化视图部分。
🐸 compile
在Vue的构造函数中对根元素进行编译
class MVue {
constructor (options) {
// 保存options
this.$options = options
this.$data = options.data
// 将data进行响应式处理
observe(this.$data)
// 代理
proxy(this)
// 编译
/**核心部分**/
new Compile(options.el, this)
}
}
class Compile {
constructor (el, vm) {
this.$vm = vm
this.$el = document.querySelector(el)
if (this.$el) {
this.compile(this.$el)
}
}
compile (node) {
// 找到该元素的子节点
const childNodes = node.childNodes
// childNodes是类数组对象
Array.from(childNodes).forEach(n => {
// 判断类型
if (this.isElment(n)) {
this.compileElement(n)
// 递归
if (n.childNodes.length > 0) {
this.compile(n)
}