什么是运行时
举个例子
<body>
<div id="app"></div>
</body>
<script>
const { render, h } = Vue
// 生成 VNode
const vnode = h('div', {
class: 'test'
}, 'hello render')
// 承载的容器
const container = document.querySelector('#app')
// 渲染函数
render(vnode, container)
</script>
以上代码代表了一个基本的 运行时。即:把 VNode 渲染到页面中。可以简单的把运行时理解为 渲染系统。
根据以上代码我们可以知道,整个 runtime,包含了两个主要的环节:
h函数:生成VNoderender函数:渲染VNode
根据以上代码可知,我们可以通过 h 函数 得到一个 vnode;然后通过render 函数把 VNode渲染到页面中。
01.vnode
打印当前的 vnode,可以得到以下内容:
{
"__v_isVNode": true,
"__v_skip": true,
"type": "div",
"props": { "class": "test" },
"key": null,
"ref": null,
"scopeId": null,
"slotScopeIds": null,
"children": "hello render",
"component": null,
"suspense": null,
"ssContent": null,
"ssFallback": null,
"dirs": null,
"transition": null,
"el": null,
"anchor": null,
"target": null,
"targetAnchor": null,
"staticCount": 0,
"shapeFlag": 9,
"patchFlag": 0,
"dynamicProps": null,
"dynamicChildren": null,
"appContext": null
}
以上内容,我们剔除掉无用的内容之后,得到一个精简的 json
{
// 是否是一个 VNode 对象
"__v_isVNode": true,
// 当前节点类型
"type": "div",
// 当前节点的属性
"props": { "class": "test" }
// 它的子节点
"children": "hello render"
}
02.render
render(vnode, container)
从以上代码中我们可知,render 函数主要接收了两个参数:
vnode:虚拟节点树 或者叫做 虚拟DOM树,两种叫法皆可container:承载的容器。真实节点渲染的位置。
通过 render 函数,我们可以:使用编程式地方式,创建虚拟 DOM 树对应的真实 DOM 树,到指定位置。