您好,登錄后才能下訂單哦!
這篇文章主要講解了“Vue3中的h函數(shù)怎么使用”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“Vue3中的h函數(shù)怎么使用”吧!
眾所周知,vue內(nèi)部構(gòu)建的其實(shí)是虛擬DOM,而虛擬DOM是由虛擬節(jié)點(diǎn)生成的,實(shí)質(zhì)上虛擬節(jié)點(diǎn)也就是一個(gè)js對(duì)象
事實(shí)上,我們?cè)趘ue中寫(xiě)的template,最終也是經(jīng)過(guò)渲染函數(shù)生成對(duì)應(yīng)的VNode
而h函數(shù)就是用來(lái)生成VNode的一個(gè)函數(shù),他的全名叫做createVNode
他一共跟三個(gè)參數(shù)
第一個(gè)參數(shù)
是一個(gè)字符串,他是必須的
這個(gè)字符串可以是 html標(biāo)簽名,一個(gè)組件、一個(gè)異步的組件或者是函數(shù)組件
第二個(gè)參數(shù)
是一個(gè)對(duì)象,可選的
與attribute、prop和事件相對(duì)應(yīng)的對(duì)象
第三個(gè)參數(shù)
可以是字符串、數(shù)組或者是一個(gè)對(duì)象
他是VNodes,使用h函數(shù)來(lái)進(jìn)行創(chuàng)建
<script> import { h } from 'vue' export default { setup() { return () => h("h4", null, "Hello World") } } </script>
渲染效果如下
當(dāng)然我們還可以使用rener函數(shù)進(jìn)行渲染
<script> import { h } from 'vue' export default { render() { return h("h4", null, "Hello World") } } </script>
計(jì)數(shù)器
<script> import { h } from 'vue' export default { data() { return { counter: 0 } }, render() { return h("div", null, [ h("h4", null, "計(jì)數(shù)器"), h("h5", null, `計(jì)數(shù)${this.counter}`), h("button", { onClick: () => this.counter++ },"點(diǎn)一下") ]) } } </script>
渲染如下
我們先寫(xiě)一個(gè)組件HelloWorld.vue
<script setup lang="ts"> import { ref } from 'vue'; const param = ref("Hello World") </script> <template> <h4>{{ param }}</h4> </template> <style scoped lang="less"></style>
然后,我們?cè)趆函數(shù)中引入這個(gè)組件,他就會(huì)被渲染
<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函數(shù)同樣支持插槽,我們把HelloWorld組件改成一個(gè)插槽組件
HelloWorld.vue
<script setup lang="ts"> import { ref } from 'vue'; const param = ref("Hello World") </script> <template> <h4>{{ param }}</h4> <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函數(shù)怎么使用”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)Vue3中的h函數(shù)怎么使用這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。