1.初始化 patch(container,vnode)
2.更新 update(vnode,newVnode)
/*
* @Autor: CQJ
* @Date: 2022-05-23 16:57:11
* @LastEditors: CQJ
* @LastEditTime: 2022-05-23 17:18:55
* @Description:
*/
function createElement(vnode) {
//虚拟dom生成三要素
let target = vnode.tag; //目标元素 ul
let attrs = vnode.attrs || {}; //属性
let children = vnode.children || []; //子元素
if (!target) {
return;
}
//1.创建对应dom
let ele = document.createElement(target);
let attrName = Object.keys(attrs);
//2.给dom添加属性
for (let i = 0; i < attrName.length; i++) {
let attr = attrName[i];
//class
ele.setAttribute(attr, attrs[attr]);
}
//3.给dom添加子元素
for (let i = 0; i < children.length; i++) {
let child = children[i];
//如果还有子元素,递归调用
ele.appendChild(createElement(child));
}
return ele;
}
function updateChildren(vnode, newVnode) {
let children = vnode.children || []; //现有节点
let newChildren = newVnode.children || []; //新节点
children.forEach((childrenVnode, index) => {
//循环每一项
let newChildrenvnode = newChildren[index];
updateElement(childrenVnode, newChildrenvnode);
});
}
function updateElement(vnode, newVnode) {
if (!newVnode) return;
if (!vnode) return;
//如果第一层的标签tag不一样,那么就需要创建新的元素
if (newVnode.tag !== vnode.tag) {
replaceChildren(childrenVnode, newChildrenvnode);
}
//如果第一层的标签一样,那么就需要更新属性,深层次对比=>递归
updateChildren(childrenVnode, newChildrenvnode);
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)