Vue3中的h函數(shù)及使用小結(jié)
參考資料:專欄目錄請點擊
簡介
- 眾所周知,vue內(nèi)部構(gòu)建的其實是虛擬DOM,而虛擬DOM是由虛擬節(jié)點生成的,實質(zhì)上虛擬節(jié)點也就是一個js對象
- 事實上,我們在vue中寫的template,最終也是經(jīng)過渲染函數(shù)生成對應(yīng)的VNode
- 而h函數(shù)就是用來生成VNode的一個函數(shù),他的全名叫做createVNode
簡單使用
參數(shù)
他一共跟三個參數(shù)

第一個參數(shù)
- 是一個字符串,他是必須的
- 這個字符串可以是 html標簽名,一個組件、一個異步的組件或者是函數(shù)組件
第二個參數(shù)
- 是一個對象,可選的
- 與attribute、prop和事件相對應(yīng)的對象
第三個參數(shù)
- 可以是字符串、數(shù)組或者是一個對象
- 他是VNodes,使用h函數(shù)來進行創(chuàng)建
使用
<script>
import { h } from 'vue'
export default {
setup() {
return () => h("h2", null, "Hello World")
}
}
</script>渲染效果如下

當然我們還可以使用rener函數(shù)進行渲染
<script>
import { h } from 'vue'
export default {
render() {
return h("h2", null, "Hello World")
}
}
</script>計數(shù)器
<script>
import { h } from 'vue'
export default {
data() {
return {
counter: 0
}
},
render() {
return h("div", null, [
h("h2", null, "計數(shù)器"),
h("h3", null, `計數(shù)${this.counter}`),
h("button", { onClick: () => this.counter++ },"點一下")
])
}
}
</script>渲染如下

進階使用
函數(shù)組件
我們先寫一個組件HelloWorld.vue
<script setup lang="ts">
import { ref } from 'vue';
const param = ref("Hello World")
</script>
<template>
<h2>{{ param }}</h2>
</template>
<style scoped lang="less"></style>然后,我們在h函數(shù)中引入這個組件,他就會被渲染
<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組件改成一個插槽組件
HelloWorld.vue
<script setup lang="ts">
import { ref } from 'vue';
const param = ref("Hello World")
</script>
<template>
<h2>{{ param }}</h2>
<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>最終渲染如下

到此這篇關(guān)于Vue3中的h函數(shù)及使用小結(jié)的文章就介紹到這了,更多相關(guān)Vue3 h函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
說說如何在Vue.js中實現(xiàn)數(shù)字輸入組件的方法
這篇文章主要介紹了說說如何在Vue.js中實現(xiàn)數(shù)字輸入組件的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
基于Vue實現(xiàn)關(guān)鍵詞實時搜索高亮顯示關(guān)鍵詞
這篇文章主要介紹了基于Vue實現(xiàn)關(guān)鍵詞實時搜索高亮顯示關(guān)鍵詞,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
vue3 el-form-item如何自定義label標簽內(nèi)容
這篇文章主要介紹了vue3 el-form-item如何自定義label標簽內(nèi)容問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
關(guān)于Vue-extend和VueComponent問題小結(jié)
這篇文章主要介紹了Vue-extend和VueComponent問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08

