Vue 中的虚拟 DOM
-
什么是虚拟 DOM?
- 虚拟 DOM 是使用 JavaScript 对象描述真实 DOM
- Vue.js 中的虚拟 DOM 借鉴 Snabbdom, 并添加了 Vue.js 的特性。例如:指令和组件机制。
-
为什么要使用虚拟 DOM ?
- 避免直接操作 DOM,提高开发效率(因为不需要操作 DOM 不需要关心操作 DOM 的浏览器兼容问题)
- 作为中间层可以跨平台(除了在 web 端使用外,还支持服务端渲染)
- 虚拟 DOM 不一定可以提高性能
- 首次渲染的时候会增加开销
- 复杂视图情况下提升渲染性能
h 函数
-
vm.$createElement(tag, data, children, normalizeChildren)
- tag
- 标签名称或者组件对象
- data
- 描述 tag, 可以设置 DOM 的属性或者标签的属性
- children
- tag 中的文本内容或者子节点
- tag
-
VNode
- h 函数的返回结果
- 核心属性
- tag
- data
- children
- text
- elm
- key
示例
<body>
<div id="app"></div>
<script src="../../dist/vue.js"></script>
<script>
const vm = new Vue({
el: '#app',
render (h) {
// h(tag, data, children)
// return h('h1', this.msg)
// return h('h1', { domProps: { innerHTML: this.msg } })
// return h('h1', { attr: { id: 'title' } }, this.msg)
const vnode = h(
'h1',
{
attrs: { id: 'title' }
},
this.msg
)
console.log(vnode)
return vnode
},
data: {
msg: 'Hello Vue'
}
});
</script>
</body>