-
snabbdom可以很好的展示出虚拟dom,虚拟dom是个抽象的概念,dom操作对于浏览器性能消耗是非常大的,虽然目前浏览器性能已经可以很大程度上忽略这一损耗,但虚拟dom带来的性能提升却是非常大的。
-
下面的例子很好的展示了虚拟dom的实现过程,以前我们用js或者jquery操作dom元素通常是更新一大块的dom元素,而snabbdom则是有变化则更新dom,没有变化则不更新dom
-
效果图
-
需求: 根据数据
data
生成如下表格,点击chang按钮,更改张三名字为小王,更改李四的年龄age
为99,然后在浏览器控制台观察dom
元素的变化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="../common.css">
</head>
<body>
<div id="container">
</div>
<button>change</button>
<script src="https://cdn.bootcdn.net/ajax/libs/snabbdom/0.7.1/snabbdom.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/snabbdom/0.7.1/snabbdom-class.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/snabbdom/0.7.1/snabbdom-props.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/snabbdom/0.7.1/snabbdom-style.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/snabbdom/0.7.1/snabbdom-eventlisteners.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/snabbdom/0.7.1/h.js"></script>
<script type="text/javascript">
//数据源
let data = [
{name: '张三', age: 18, address: '北京'},
{name: '李四', age: 19, address: '上海'},
{name: '王五', age: 20, address: '广州'}
]
//加上个表头
data.unshift({name: 'name', age: 'age', address: 'address'})
let container = document.querySelector('#container')
let btn = document.querySelector('button')
//获取snabbdom
let snabbdom = window.snabbdom
//初始化
let patch = snabbdom.init([
snabbdom_class,
snabbdom_props,
snabbdom_style,
snabbdom_eventlisteners
])
//h函数 类似于createElement
let h = snabbdom.h
let vnode = null
function render(data) {
let newnode = h('table', {}, data.map(item => {
let tds = []
for (let key in item) {
//判断是否自身属性
if (item.hasOwnProperty(key)) {
tds.push(h('td', {}, item[key]))
}
}
return h('tr', {}, tds)
}))
if (vnode) {
//非初次渲染
patch(vnode, newnode)
} else {
//初次渲染
patch(container, newnode)
}
//更新节点
vnode = newnode
}
//渲染dom
render(data)
//按键change
btn.addEventListener('click', function () {
data[1].name = '小王',
data[2].age = 99
render(data)
})
</script>
</body>
</html>
- snabbdom核心API