虚拟DOM的实现
使用虚拟DOM的原因: 减少回流与重绘
将DOM结构转换成对象保存到内存中
<img /> => { tag: 'img'}
文本节点 => { tag: undefined, value: '文本节点' }
<img title="1" class="c" /> => { tag: 'img', data: { title = "1", class="c" } }
<div><img /></div> => { tag: 'div', children: [{ tag: 'div' }]}
根据上面可以写出虚拟DOM的数据结构
class VNode {
constructor(tag, data, value, type) {
this.tag = tag && tag.toLowerCase()
this.data = data
this.value = value
this.type = type
this.children = []
}
appendChild(vnode){
this.children.push(vnode)
}
}
可能用到的基础知识
- 判断元素的节点类型:
node.nodeType
let nodeType = node.nodeType
if(nodeType == 1) {
// 元素类型
} else if (nodeType == 3) {
// 节点类型
}
- 获取元素类型的标签名和属性 && 属性中具体的键值对,保存在一个对象中
let nodeName = node.nodeName // 标签名
let attrs = node.attributes // 属性
let _attrObj = {
} // 保存各个具体的属性的键值对,相当于虚拟DOM中的data属性
for(let i =0, len = attrs.length; i< len; i++){
_attrObj[attrs[i].nodeName] = attrs[i].nodeValue
}
- 获取当前节点的子节点
let childNodes = node.childNodes
for(let i = 0, len = childNodes.length; i < len; i++){
console.log(childNodes[i])
}
算法思路</