简述VUE1和2版本的设计理念:
vue1是没有虚拟dom的 每次更新的时候把原始的dom销毁 然后创建新的替换
vue2有了虚拟dom(它的本质是js对象 他是和真实的dom一一对应的, 通过对比vnode更新视图) 他的特点是 初始化慢(因为多虚拟dom) 更新快(虚拟和真实的js对象对比,然后更新不同的地方)
下面上代码
在这里插入代码片
// 虚拟dom(vnode) => 真实dom
// vue 渲染第一条线(创建) 1次
function createElement(vnode) {
let tag = vnode.tag;
let attrs = vnode.attrs || {};
let children = vnode.children || [];
if(!tag) {
return null
}
let elem = document.createElement(tag); //创建目标元素
let attrName;
for(attrName in attrs) {
// 判断元素是否有此属性名
if(attrs.hasOwnProperty(attrName)) {
// 给属性 添加对应的属性值
elem.setAttribute(attrName,attrs[attrName])
}
}
// 添加对应的子节点
children.forEach(function(childVnode) {
// 递归添加深层子节点
elem.appendChild(createElement(childVnode));
})
return elem;
}
// vue 渲染第二条线(更新) n次
function updateChildren(vnode,newVnode) {
let children = vnode.childre || [];
let newchildren = newVnode.children || [];
children.forEach(function(childrenVnode,index){
let newchildrenVnode = newChildren[index];
// 新老元素对比
if(childrenVnode.tag === newchildrenVnode.tag) {
// 深层级 继续 对比
updateChildren(childrenVnode, newchildrenVnode)
}
else {
// 两者不一样 替换
replaceNode(childrenVnode,newchildrenVnode)
}
})
}