这次将目光放在 el 上
new Vue({
el: "#app"
})
来实现一下
<div id="app">
<div>sdiahbdosdo</div>
<div>balabala....</div>
</div>
<script>
let module;
module = new Vey({
el: '#app'
})
</script>
原理其实还是简单, 构建一个虚拟节点的模型, 把 #app
拿到的dom
节点, 遍历一遍, 根据节点的nodeType
, 将它们分门别类
function Vey(options) {
this.el = options.el
this.data = options.data
this.VNode = null
// 拿到数据之后, 需要对它进行一些操作, 即重写 getter setter
// initData.call(this, this.data)
let el = document.querySelector(this.el)
this.VNode = buildVirtualNode(el)
console.log(this.VNode)
}
function VNode (dom, type, value) {
this.dom = dom
this.type = type
this.value = value
this.childNodes = []
this.appendChild = function (node) {
if(!(node instanceof VNode)){
throw new Error('node is not instanceof VNode')
} else {
this.childNodes.push(node)
}
}
}
function buildVirtualNode (root) {
let temp = new VNode(root, root.nodeType, root.nodeValue)
for (let i = 0; i < root.childNodes.length; i ++ ){
if(root.childNodes[i].nodeType === 1) { // dom 节点
let child = buildVirtualNode(root.childNodes[i])
temp.appendChild(child)
} else if (root.childNodes[i].nodeType === 3) { // 文本节点
let child = buildVirtualNode(root.childNodes[i])
temp.appendChild(child)
} else {
continue
}
}
return temp
}
1.png
网友评论