背景:当原生js与jquery对DOM(文件对象模型)操作时,DOM Tree会被重新构建与绘制。(消耗浏览器资源,具体表现为页面卡顿)
利用js运行速度快的特性,建立了virtual DOM
原理:
- js对象模拟DOM Tree并渲染DOM Tree
- 利用diff策略(比较新旧DOM Tree),获得差异的对象。
- 差异的对象应用到渲染的DOM Tree
举例:
真实DOM
<div id="app">
123
<div>123</div>
</div>
虚拟DOM(js实现)
var vNode = {
tag: 'div',
props: {id: 'app'},
children: [
{
tag: 'div',
props: {},
children: [],
context: '123'
}
],
context: '123'
}
实现方法
function createComponent(tag) {
let child = [];
for(let i = 0; i < tag.children.length; i++) {
if(tag.children[i].children.length <= 0) {
child[i] = {
tag: tag.children[i].nodeName.toLowerCase(),
props: tag.children[i].attributes,
context: tag.children[i].innerText,
children: []
};
} else {
child[i] = createComponent(tag.children[i]);
}
}
let vNode = {
tag: tag.nodeName.toLowerCase(),
props: tag.attributes,
children: child,
context: tag.childNodes[0].nodeValue
}
return vNode;
}