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>

完美获取,好,下课。

相关推荐
y***54882 分钟前
前端构建工具扩展,Webpack插件开发
前端·webpack·node.js
4***14903 分钟前
前端构建工具多页面配置,Webpack与Vite
前端·webpack·node.js
网络点点滴13 分钟前
标签的ref属性
前端·javascript·vue.js
天若有情6731 小时前
前端 vs 后端:入行软件行业,我该如何选择?哪个更“简单”?
前端·后端·软件开发·职业·就业·选择
小画家~1 小时前
第二十八:golang Time.time 时间格式返回定义结构体
java·前端·golang
Cobyte2 小时前
17. Vue3 业务组件库按需加载的实现原理
前端·javascript·vue.js
粥里有勺糖2 小时前
视野修炼-技术周刊第127期 | Valdi
前端·javascript·github
前端世界2 小时前
从零搭建 ASP.NET 单文件 Web 项目:一个能真用的 BookShop 管理页实战
服务器·前端·asp.net
码上成长2 小时前
Vue Router 3 升级 4:写法、坑点、兼容一次讲透
前端·javascript·vue.js
BBB努力学习程序设计2 小时前
响应式页面设计与实现:让网站适配所有设备的艺术
前端·html