Vue3中h函數(shù)超詳細(xì)教程(附示例與應(yīng)用場景)
前言
??適合初中高級 Vue 3 開發(fā)者,了解 Composition API、JSX/TSX 或 render 函數(shù)寫法的同學(xué)
一、什么是h函數(shù)?
在 Vue 3 中,h 是創(chuàng)建虛擬 DOM(VNode)的工具函數(shù),常用于渲染函數(shù)中,替代 Vue 2 中的 createElement。
h 是 hyperscript 的縮寫,代表用 JS 語法構(gòu)造虛擬 DOM 樹結(jié)構(gòu)。
二、語法結(jié)構(gòu)與基本用法
h( type, // string | Component | object props?, // object | null children? // string | array | object | function )
參數(shù)詳解:
| 參數(shù) | 說明 |
|---|---|
type | 標(biāo)簽名(如 'div')或組件引用 |
props | 元素屬性或組件 props,例如 class、onClick 等 |
children | 子節(jié)點,可以是字符串、數(shù)組、VNode,或插槽函數(shù)等 |
三、使用場景詳解與示例
1. 普通元素渲染(替代模板語法)
import { h } from 'vue'
export default {
render() {
return h('div', { class: 'hello' }, 'Hello World')
}
}
效果等同于:
<template> <div class="hello">Hello World</div> </template>
2. 嵌套結(jié)構(gòu)組件
export default {
render() {
return h('div', { class: 'wrapper' }, [
h('h2', '標(biāo)題'),
h('p', '段落內(nèi)容'),
h('button', { onClick: this.handleClick }, '點擊')
])
},
methods: {
handleClick() {
alert('點擊了按鈕!')
}
}
}
3. 渲染組件(傳遞 props 和插槽)
import { h } from 'vue'
import MyButton from './MyButton.vue'
export default {
render() {
return h(MyButton, { type: 'primary', onClick: this.doSomething }, {
default: () => '點我'
})
},
methods: {
doSomething() {
console.log('點擊按鈕!')
}
}
}
4. 組合 JSX/TSX 使用(推薦)
如果你啟用了 TSX/JSX,使用 h 更加自然:
import { defineComponent } from 'vue'
export default defineComponent({
setup() {
return () => (
<div class="box">
<p>Hello JSX</p>
</div>
)
}
})
?? 需要配置
vite.config.ts啟用 JSX 插件:
import vueJsx from '@vitejs/plugin-vue-jsx'
export default {
plugins: [vueJsx()]
}
四、常見擴(kuò)展應(yīng)用
動態(tài)渲染表格列(Element Plus 示例)
render() {
return h('el-table-column', {
prop: 'name',
label: '姓名',
scopedSlots: {
default: (scope) => h('span', scope.row.name)
}
})
}
??注意:Vue 3 移除了
scopedSlots,需改為 slot 函數(shù)形式:
render() {
return h(ElTableColumn, { prop: 'name', label: '姓名' }, {
default: ({ row }) => h('span', row.name)
})
}
結(jié)合vnode動態(tài)插槽場景
render() {
return h(MyComponent, {}, {
default: () => '默認(rèn)插槽內(nèi)容',
header: () => h('h1', '頭部插槽')
})
}
五、總結(jié):何時使用h
| 需求 | 是否使用 h |
|---|---|
| 模板編寫簡單 UI | ? 推薦使用 <template> |
| 組件庫封裝 / 高階組件 | ? 使用 render 函數(shù)或 h |
| 動態(tài)插槽渲染 | ? 推薦用 h |
| 插件 / 指令 / 動態(tài) DOM | ? 推薦用 h |
| 使用 JSX/TSX 時 | ? 使用 h 或 JSX |
附錄:Vue 官方h類型定義(簡化)
function h( type: string | Component, props?: object | null, children?: string | VNode[] | () => VNode ): VNode
你也可以從 Vue 內(nèi)部導(dǎo)出它:
import { h } from 'vue'
到此這篇關(guān)于Vue3中h函數(shù)超詳細(xì)教程的文章就介紹到這了,更多相關(guān)Vue3 h函數(shù)詳解內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue 2 實現(xiàn)自定義組件一到多個v-model雙向數(shù)據(jù)綁定的方法(最新推薦)
有時候我們需要對一個組件綁定自定義 v-model,以更方便地實現(xiàn)雙向數(shù)據(jù),例如自定義表單輸入控件,這篇文章主要介紹了vue 2 實現(xiàn)自定義組件一到多個v-model雙向數(shù)據(jù)綁定的方法,需要的朋友可以參考下2024-07-07
element-plus的自動導(dǎo)入和按需導(dǎo)入方式詳解
之前使用 ElementPlus 做項目的時候,由于不會使用按需引入耽誤了不少時間,這篇文章主要給大家介紹了關(guān)于element-plus自動導(dǎo)入和按需導(dǎo)入的相關(guān)資料,需要的朋友可以參考下2022-08-08

