Vue3中h函数超详细教程(附示例与应用场景)
作者:JaysonJin
这篇文章主要给大家介绍了关于Vue3中h函数的相关资料,h函数是Vue3中用来创建虚拟节点(VNode)的工具,它的本质是createVNode方法的简写,文中通过代码介绍的非常详细,需要的朋友可以参考下
前言
💡适合初中高级 Vue 3 开发者,了解 Composition API、JSX/TSX 或 render 函数写法的同学
一、什么是h函数?
在 Vue 3 中,h 是创建虚拟 DOM(VNode)的工具函数,常用于渲染函数中,替代 Vue 2 中的 createElement。
h 是 hyperscript 的缩写,代表用 JS 语法构造虚拟 DOM 树结构。
二、语法结构与基本用法
h( type, // string | Component | object props?, // object | null children? // string | array | object | function )
参数详解:
| 参数 | 说明 |
|---|---|
type | 标签名(如 'div')或组件引用 |
props | 元素属性或组件 props,例如 class、onClick 等 |
children | 子节点,可以是字符串、数组、VNode,或插槽函数等 |
三、使用场景详解与示例
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()]
}
四、常见扩展应用
动态渲染表格列(Element Plus 示例)
render() {
return h('el-table-column', {
prop: 'name',
label: '姓名',
scopedSlots: {
default: (scope) => h('span', scope.row.name)
}
})
}
⚠️注意:Vue 3 移除了
scopedSlots,需改为 slot 函数形式:
render() {
return h(ElTableColumn, { prop: 'name', label: '姓名' }, {
default: ({ row }) => h('span', row.name)
})
}
结合vnode动态插槽场景
render() {
return h(MyComponent, {}, {
default: () => '默认插槽内容',
header: () => h('h1', '头部插槽')
})
}
五、总结:何时使用h
| 需求 | 是否使用 h |
|---|---|
| 模板编写简单 UI | ❌ 推荐使用 <template> |
| 组件库封装 / 高阶组件 | ✅ 使用 render 函数或 h |
| 动态插槽渲染 | ✅ 推荐用 h |
| 插件 / 指令 / 动态 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函数超详细教程的文章就介绍到这了,更多相关Vue3 h函数详解内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
