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 分钟前
让 CLI 更友好:在 npm 包里同时支持“命令行传参”与“交互式对话传参”
前端·npm
Mintopia12 分钟前
🐋 用 Docker 驯服 Next.js —— 一场前端与底层的浪漫邂逅
前端·javascript·全栈
Mintopia14 分钟前
物联网数据驱动 AIGC:Web 端设备状态预测的技术实现
前端·javascript·aigc
一个W牛30 分钟前
报文比对工具(xml和sop)
xml·前端·javascript
鸡吃丸子44 分钟前
浏览器是如何运作的?深入解析从输入URL到页面渲染的完整过程
前端
作业逆流成河1 小时前
🔥 enum-plus 3.0:介绍一个天花板级的前端枚举库
前端·javascript·前端框架
爱喝水的小周1 小时前
《UniApp 页面导航跳转全解笔记》
前端·uni-app
蒜香拿铁1 小时前
Angular【组件】
前端·javascript·angular.js
ByteCraze1 小时前
一文讲透 npm 包版本管理规范
前端·arcgis·npm
梵得儿SHI1 小时前
Vue 模板语法深度解析:从文本插值到 HTML 渲染的核心逻辑
前端·vue.js·html·模板语法·文本插值·v-text指令·v-html指令