1、第一次创建dom(patch方法)大致流程:
function patch(vnode) {
let tag = vnode.tag; //目标元素
let attrs = vnode.attrs || {}; //属性
let children = vnode.children || []; //子节点
if (!tag) {
return null;
}
// 1.创建对应的节点
let elem = document.createElement(tag);
let attrName;
// 2.给dom添加属性
for (attrName in attrs) {
if (attrs.hasOwnProperty(attrName)) {
elem.setAttribute(attrName, attrs[attrName]); //class style……
}
}
// 3.将子元素添加到目标元素上
children.forEach(function (childVnode) {
elem.appendChild(patch(childVnode));
});
return elem;
}
2、更新dom(update方法):
function update(vnode, newVnode){
let children = vnode.children || [] //现有节点
let newChildren = newVnode.children || [] //新节点
children.forEach(function(childrenVnode,index) {
let newChildrenVnode = newChildren[index]
//第一层没有变化,继续找下一层
if(childrenVnode.tag === newChildrenVnode.tag){
update(childrenVnode, newChildrenVnode)
} else {
// vue自带函数,更新变化节点
replaceNode(childrenVnode, newChildrenVnode)
}
})
}