vue3+typescript+elemnt plus 封装一个table表格组件
以下是一个简单的基于Vue3、TypeScript和Element Plus的表格组件封装示例:
<template>
<el-table :data="tableData" :border="border" :stripe="stripe" :height="height">
<slot name="columns">
<el-table-column v-for="column in columns" :key="column.prop" :prop="column.prop" :label="column.label">
<template v-if="column.type && column.type === 'index'" #default="{index}">{{ index + 1 }}</template>
<template v-if="column.type && column.type === 'status'" #default="{row}">{{ getStatusText(row[column.prop]) }}</template>
<template v-if="column.type && column.type === 'action'" #default="{row}">
<el-button v-for="action in column.actions" :key="action.label" :type="action.type" @click="handleAction(action, row)">{{ action.label }}</el-button>
</template>
</el-table-column>
</slot>
</el-table>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElTable, ElTableColumn, ElButton } from 'element-plus';
export default defineComponent({
name: 'MyTable',
components: { ElTable, ElTableColumn, ElButton },
props: {
columns: { type: Array, required: true },
tableData: { type: Array, required: true },
border: { type: Boolean, default: true },
stripe: { type: Boolean, default: true },
height: { type: [String, Number] },
},
methods: {
getStatusText(status: number) {
return status === 1 ? '启用' : '禁用';
},
handleAction(action: any, row: any) {
action.handler(row);
},
},
});
</script>
在上述代码中,我们通过<slot>标签将表格列定义抽象出来,使得该组件可以适应各种不同的表格数据。同时,我们还提供了一些通用的功能,例如显示序号、显示状态文本、执行操作等。这些功能可以通过在columns数组中添加特定的属性来实现。例如,对于类型为index的列,我们可以在columns中这样定义:
{
label: '序号',
type: 'index',
}
由于<el-table>和<el-table-column>都是Element Plus提供的组件,因此我们需要在<script>中通过import语句将它们引入。在<script>中,我们还定义了组件的名字、props和methods。其中,getStatusText和handleAction方法都是针对特定列类型的通用方法,可以通过columns数组中的type属性来调用。例如,在columns中这样定义一个类型为status的列:
{
label: '状态',
prop: 'status',
type: 'status',
}
在这个列中,我们需要根据status属性的值来显示不同的文本。因此,我们通过getStatusText方法来实现这个功能。另外,如果我们在columns中定义了一个类型为action的列,那么我们可以在actions数组中添加各种不同的操作,例如:
{
label: '操作',
type: 'action',
prop: 'id',
actions: [
{ label: '编辑', type: 'primary', handler: (row) => { /* 执行编辑操作 */ } },
{ label: '删除', type: 'danger', handler: (row) => { /* 执行删除操作 */ } },
],
}
通过这种方式,我们可以很方便地为表格添加各种不同的操作,而不需要每次都写一遍重复的代码。
原文地址: https://www.cveoy.top/t/topic/b9Nt 著作权归作者所有。请勿转载和采集!