h 函数的原理就是 createVNode。可以使用 h 函数封装一些小组件。
<template>
<table border>
<tr>
<th>name</th>
<th>age</th>
<th>操作</th>
</tr>
<tr v-for="item in list" :key="item.age">
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<Btn type="success">编辑</Btn>
<Btn type="error">删除</Btn>
</td>
</tr>
</table>
</template>
<script setup lang="ts">
import {reactive, h} from "vue";
const list = reactive([
{name: 111, age: 12},
{name: 333, age: 23},
{name: 444, age: 44}
])
interface Props {
type: 'success' | 'error'
}
const Btn = (props: Props, ctx: any) => {
// 第一个参数是创建的结点,第二个属性是结点的属性,第三个结点是结点的内容
return h('button', {
style: {
color: props.type === 'success' ? 'green' : 'red'
},
onClick: () => {
// ctx.emit('click',222)
if (props.type === 'success') {
console.log('编辑')
} else {
console.log('删除')
}
}
}, ctx.slots.default())
}
</script>
<style scoped lang="less">
</style>

setup返回的render函数优先级高于template

本文介绍了如何在Vue中使用h函数封装小组件,如表格,展示如何通过props传递类型并处理点击事件。展示了如何创建动态按钮,根据不同prop显示不同的颜色并执行相应的操作。
109

被折叠的 条评论
为什么被折叠?



