一、组件components/MyTable.vue
<template>
<el-table v-bind="$attrs" :data="tableData" >
<el-table-column v-for="item in column" :key="item.prop" v-bind="item" align="center">
<template #default="scope" v-if="$slots[item.prop]">
<slot :name="item.prop" v-bind="scope"></slot>
</template>
<template #add="scope" v-if="$slots[item.prop]">
<slot :name="item.prop" v-bind="scope"></slot>
</template>
</el-table-column>
</el-table>
</template>
<script setup lang='ts'>
interface TableData {
[propName: string]: any;
}
interface Column {
prop: string;
label: string;
[propName: string]: any;
}
defineProps<{
tableData: TableData[];
column: Column[];
}>();
</script>
<style lang='scss' scoped>
</style>
二、页面使用
<template>
<div>
<my-table :tableData="tableData" :column="column">
<template #operation="scope">
<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button size="small" type="primary" @click="handleAdd(scope.$index, scope.row)">增加</el-button>
</template>
</my-table>
</div>
</template>
<script setup lang="ts">
import myTable from '../components/MyTable.vue';
interface User {
date: string
name: string
address: string
}
const tableData: User[] = [
{
date: '2023-05-03',
name: '小黑',
address: '石家庄市长安区东古城村',
},
{
date: '2023-05-02',
name: '小白',
address: '石家庄市长安区东古城村',
},
{
date: '2023-05-04',
name: '小红',
address: '石家庄市长安区东古城村',
},
{
date: '2023-05-01',
name: '小绿',
address: '石家庄市长安区东古城村',
},
]
const column = [
{
prop: 'date',
label: '日期',
width: '180'
},
{
prop: 'name',
label: '姓名',
width: '180'
},
{
prop: 'address',
label: '地址'
},
{
prop: 'operation',
label: '操作'
}
]
const handleEdit = (index: number, row: User) => {
console.log(index, row)
}
const handleAdd = (index: number, row: User) => {
console.log(index, row)
}
</script>
三、效果