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>

完美获取,好,下课。

相关推荐
失忆爆表症6 小时前
05_UI 组件库集成指南:Shadcn/ui + Tailwind CSS v4
前端·css·ui
小迷糊的学习记录6 小时前
Vuex 与 pinia
前端·javascript·vue.js
发现一只大呆瓜6 小时前
前端性能优化:图片懒加载的三种手写方案
前端·javascript·面试
不爱吃糖的程序媛6 小时前
Flutter 与 OpenHarmony 通信:Flutter Channel 使用指南
前端·javascript·flutter
利刃大大6 小时前
【Vue】Element-Plus快速入门 && Form && Card && Table && Tree && Dialog && Menu
前端·javascript·vue.js·element-plus
NEXT067 小时前
AI 应用工程化实战:使用 LangChain.js 编排 DeepSeek 复杂工作流
前端·javascript·langchain
念风零壹7 小时前
AI 时代的前端技术:从系统编程到 JavaScript/TypeScript
前端·ai
光影少年7 小时前
react的hooks防抖和节流是怎样做的
前端·javascript·react.js
小毛驴8507 小时前
Vue 路由示例
前端·javascript·vue.js
发现一只大呆瓜8 小时前
AI流式交互:SSE与WebSocket技术选型
前端·javascript·面试