简介众所周知,vue内部构建的其实是虚拟dom,而虚拟dom是由虚拟节点生成的,实质上虚拟节点也就是一个js对象
事实上,我们在vue中写的template,最终也是经过渲染函数生成对应的vnode
而h函数就是用来生成vnode的一个函数,他的全名叫做createvnode
简单使用参数他一共跟三个参数
第一个参数
是一个字符串,他是必须的
这个字符串可以是 html标签名,一个组件、一个异步的组件或者是函数组件
第二个参数
是一个对象,可选的
与attribute、prop和事件相对应的对象
第三个参数
可以是字符串、数组或者是一个对象
他是vnodes,使用h函数来进行创建
使用<script>import { h } from 'vue'export default { setup() { return () => h("h3", null, "hello world") }}</script>
渲染效果如下
当然我们还可以使用rener函数进行渲染
<script>import { h } from 'vue'export default { render() { return h("h3", null, "hello world") }}</script>
计数器
<script>import { h } from 'vue'export default { data() { return { counter: 0 } }, render() { return h("div", null, [ h("h3", null, "计数器"), h("h4", null, `计数${this.counter}`), h("button", { onclick: () => this.counter++ },"点一下") ]) }}</script>
渲染如下
进阶使用函数组件我们先写一个组件helloworld.vue
<script setup lang="ts">import { ref } from 'vue';const param = ref("hello world") </script><template> <h3>{{ param }}</h3></template><style scoped lang="less"></style>
然后,我们在h函数中引入这个组件,他就会被渲染
<script>import { h } from 'vue'import helloworld from './helloworld.vue'export default { data() { return { counter: 0 } }, render() { return h("div", null, [h(helloworld)]) }}</script>
插槽h函数同样支持插槽,我们把helloworld组件改成一个插槽组件
helloworld.vue
<script setup lang="ts">import { ref } from 'vue';const param = ref("hello world") </script><template> <h3>{{ param }}</h3> <slot></slot></template><style scoped lang="less"></style>
index.ts
<script>import { h } from 'vue'import helloworld from './helloworld.vue'export default { data() { return { counter: 0 } }, render() { return h("div", null, [h(helloworld, {}, [h("div", null, "hello slot")])]) }}</script>
最终渲染如下
以上就是vue3中的h函数如何使用的详细内容。