vue3.5泛型组件和useTemplateRef获取组件实例

vue3.3更新了generic泛型组件,赶快学起来,更好的封装你的组件把

之前vue3.3的时候写了一篇关于泛型组件的文章,当时的用ref获取组件实例的时候,有点问题。现在出了新的useTemplateRef hook,解决了ref获取不到组件实例的问题。关于泛型组件,可以看上一篇文章,这里不浪费大家的时间了,直接上代码。

泛型组件的意义在于,这个组件是公用的,所以组件props类型不能写死

js 复制代码
// Table.vue
<template>
    <table>
        <thead>
            <tr>
                <th v-for="(item, index) in columns" :key="index">{{ item.title }}</th>
            </tr>
        </thead>
        <tbody>
            <tr v-for="(item, index) in dataSource" :key="index">
                <td v-for="header in columns">
                    <slot name="bodyCell" :record="item" :column="header">
                        {{ item[header.dataIndex] }}
                    </slot>
                </td>
            </tr>
        </tbody>
    </table>
</template>

<script setup lang="ts" generic="T extends object">
defineProps<{
    columns: { title: string; dataIndex: keyof T; key: string }[]
    dataSource: T[]
}>()

defineExpose({
    /** 清除 */
    clear() {
        console.log('clear')
    },
})
</script>
js 复制代码
//App.vue
<template>
    <Table :dataSource="dataSource" :columns="columns" ref="table">
        <template #bodyCell="{ record, column }">
            <span v-if="column.dataIndex === 'name'">{{ record.name }}</span>
        </template>
    </Table>
</template>

<script setup lang="ts">
import Table from './components/Table.vue'
import { onMounted, useTemplateRef } from 'vue'

const table = useTemplateRef('table')

interface IDataSource {
    key: string
    name: string
    age: number
    address: string
}

interface IColumns {
    title: string
    dataIndex: keyof IDataSource
    key: string
}
const dataSource: IDataSource[] = [
    {
        key: '1',
        name: 'Mike',
        age: 32,
        address: '10 Downing Street',
    },
    {
        key: '2',
        name: 'John',
        age: 42,
        address: '10 Downing Street',
    },
]

const columns: IColumns[] = [
    {
        title: 'Name',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: 'Age',
        dataIndex: 'age',
        key: 'age',
    },
    {
        title: 'Address',
        dataIndex: 'address',
        key: 'address',
    },
]

onMounted(() => {
    table.value?.clear()
})
</script>

完美获取,好,下课。

相关推荐
m0_471199633 分钟前
【自动化】前端开发,如何将 Jenkins 与 Gitee 结合实现自动化的持续集成(构建)和持续部署(发布)
前端·gitee·自动化·jenkins
w***95494 分钟前
spring-boot-starter和spring-boot-starter-web的关联
前端
Moment8 分钟前
富文本编辑器技术选型,到底是 Prosemirror 还是 Tiptap 好 ❓❓❓
前端·javascript·面试
xkxnq13 分钟前
第二阶段:Vue 组件化开发(第 18天)
前端·javascript·vue.js
晓得迷路了14 分钟前
栗子前端技术周刊第 112 期 - Rspack 1.7、2025 JS 新星榜单、HTML 状态调查...
前端·javascript·html
怕浪猫17 分钟前
React从入门到出门 第五章 React Router 配置与原理初探
前端·javascript·react.js
jinmo_C++17 分钟前
从零开始学前端 · HTML 基础篇(一):认识 HTML 与页面结构
前端·html·状态模式
鹏多多23 分钟前
前端2025年终总结:借着AI做大做强再创辉煌
前端·javascript
WebGISer_白茶乌龙桃29 分钟前
Cesium实现“悬浮岛”式,三维立体的行政区划
javascript·vue.js·3d·web3·html5·webgl
小Tomkk32 分钟前
⭐️ StarRocks Web 使用介绍与实战指南
前端·ffmpeg