Vue3中h函數(shù)超詳細教程(附示例與應用場景)
前言
??適合初中高級 Vue 3 開發(fā)者,了解 Composition API、JSX/TSX 或 render
函數(shù)寫法的同學
一、什么是h函數(shù)?
在 Vue 3 中,h
是創(chuàng)建虛擬 DOM(VNode)的工具函數(shù),常用于渲染函數(shù)中,替代 Vue 2 中的 createElement
。
h 是 hyperscript 的縮寫,代表用 JS 語法構造虛擬 DOM 樹結構。
二、語法結構與基本用法
h( type, // string | Component | object props?, // object | null children? // string | array | object | function )
參數(shù)詳解:
參數(shù) | 說明 |
---|---|
type | 標簽名(如 '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. 嵌套結構組件
export default { render() { return h('div', { class: 'wrapper' }, [ h('h2', '標題'), h('p', '段落內容'), 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()] }
四、常見擴展應用
動態(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) }) }
結合vnode動態(tài)插槽場景
render() { return h(MyComponent, {}, { default: () => '默認插槽內容', header: () => h('h1', '頭部插槽') }) }
五、總結:何時使用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 內部導出它:
import { h } from 'vue'
到此這篇關于Vue3中h函數(shù)超詳細教程的文章就介紹到這了,更多相關Vue3 h函數(shù)詳解內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
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