本篇文章将介绍中后台系统中列表页中的表格控件,基于el-table做的二次封装
- 支持可配置的方式渲染table column
- 支持表单编辑,校验
效果展示
用法demo
<script setup lang="ts">
interface IState {
editingRowKeys: string[]
tableData: any
schemas: any
}
const columns = [
{
type: 'selection',
width: 38,
},
// 继承了table-column的所有属性,拓展了2个属性,slot和extraEditConfig
{
prop: 'a',
label: $t('标题'),
// 表单编辑配置项
extraEditConfig: {
// 是否可编辑
editable: true,
// 表单项组件
component: {
// 组件名或者组件本身
vm: BaseSelect,
// 组件属性
props: {
api: async () => {}
apiParams: {},
multiple: false,
},
/// 组件事件
listeners: {},
},
// 当表单项处于未正在编辑的状态,支持三种形态展示 1文本:text 2只读态:readonly 3禁用态:disabled
unEditingType: 'disabled',
// 表单校验规则
rules: [
{
required: true,
message: $t('请选择'),
trigger: 'change',
},
],
},
},
{
prop: 'b',
label: $t('标题'),
extraEditConfig: {
editable: true,
component: {
vm: 'el-input',
props: {},
listeners: {},
},
unEditingType: 'text',
rules: [
{
required: true,
message: $t('请输入'),
trigger: 'blur',
},
],
},
},
{
prop: 'c',
label: $t('是否开启'),
extraEditConfig: {
editable: true,
component: {
vm: 'el-switch',
props: {},
listeners: {},
},
unEditingType: 'disabled',
},
},
{
label: $t('操作'),
slot: 'operation',
width: 130,
},
]
const baseTable = ref()
const state = reactive<IState>({
// 正在编辑中的行
editingRowKeys: ['1', '2', '3'],
// 表格数据
tableData: [
{
id: '1',
a: '11111',
b: 2,
c: 1,
},
],
})
async function onEdit(row: any) {
// await toValue(baseTable).form.validate((valid, fields) => {
// if (valid)
// console.log('submit!')
// else
// console.log('error submit!', fields)
// })
const index = state.editingRowKeys.findIndex(key => key === row.id)
if (index === -1)
state.editingRowKeys.push(row.id)
else
state.editingRowKeys.splice(index, 1)
}
</script>
<template>
// 继承了el-table所有属性,拓展了columns,data,editingRowKeys三个属性
<BaseTable
ref="baseTable"
row-key="id"
:columns="columns"
:data="state.tableData"
:editing-row-keys="state.editingRowKeys"
>
<template #operation="{ row }">
<ElButton @click="onEdit(row)">
{{ state.editingRowKeys.includes(row.id) ? $t('取消编辑') : $t('编辑') }}
</ElButton>
</template>
</BaseTable>
</template>
最后
BaseTable组件的代码可以在后续开源后再查看,欢迎大家一起探讨。