Home > Article > Web Front-end > How to use the h function in Vue3
As we all know, what is built inside vue is actually a virtual DOM, and the virtual DOM is generated by a virtual node. In essence, the virtual node is a js object
In fact, the template we write in vue ultimately generates the corresponding VNode through the rendering function
And the h function is used to generate VNode Function, its full name is createVNode
It has three parameters in total
The first parameter
is a string, it is required
This The string can be an html tag name, a component, an asynchronous component or a function component
The second parameter
is an object, optional
Object corresponding to attribute, prop and event
The third one Parameters
can be a string, an array or an object
It is VNodes and is created using the h function
<script> import { h } from 'vue' export default { setup() { return () => h("h3", null, "Hello World") } } </script>
The rendering effect is as follows
##Of course we can also use the rener function for rendering<script> import { h } from 'vue' export default { render() { return h("h3", null, "Hello World") } } </script>Counter
<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>Rendered as follows Advanced useFunction componentLet’s write a component first
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>Then, we introduce this component in the h function, and it will be rendered
<script> import { h } from 'vue' import HelloWorld from './HelloWorld.vue' export default { data() { return { counter: 0 } }, render() { return h("div", null, [h(HelloWorld)]) } } </script>Slot
h function also supports slots, we change the HelloWorld component into a slot component
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>The final rendering is as follows
The above is the detailed content of How to use the h function in Vue3. For more information, please follow other related articles on the PHP Chinese website!