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>

完美获取,好,下课。

相关推荐
斯~内克4 小时前
Electron 菜单系统深度解析:从基础到高级实践
前端·javascript·electron
数据知道4 小时前
【YAML】一文掌握 YAML 的详细用法(YAML 备忘速查)
前端·yaml
清风絮柳4 小时前
51. “闲转易”交易平台小程序(基于springboot&vue)
vue.js·spring boot·小程序·毕业设计·校园二手交易平台·二手交易小程序·闲转易交易系统
dr李四维4 小时前
vue生命周期、钩子以及跨域问题简介
前端·javascript·vue.js·websocket·跨域问题·vue生命周期·钩子函数
旭久4 小时前
react+antd中做一个外部按钮新增 表格内部本地新增一条数据并且支持编辑删除(无难度上手)
前端·javascript·react.js
windyrain4 小时前
ant design pro 模版简化工具
前端·react.js·ant design
浪遏5 小时前
我的远程实习(六) | 一个demo讲清Auth.js国外平台登录鉴权👈|nextjs
前端·面试·next.js
GISer_Jing5 小时前
React-Markdown详解
前端·react.js·前端框架
太阳花ˉ5 小时前
React(九)React Hooks
前端·react.js