refactor(table): 优化表格组件数据处理逻辑

- 调整 CuteDragTable 组件中分页器的位置,将其移至表格外部
- 简化数据获取流程,将 response 变量改为 transformData 并优化数据转换逻辑
- 移除不必要的返回语句和注释代码
- 修复 CuteDragTableDemo 中表单参数传递问题,直接使用 this.form 而非 this.form.model
- 从 CuteSimpleTableDemo 中移除硬编码的列配置数组
This commit is contained in:
2026-02-06 14:55:31 +08:00
parent cebceeac1a
commit 56046c6b6e
10 changed files with 472 additions and 37 deletions
@@ -0,0 +1,12 @@
import request from '@/utils/request'
export function searchMenu(query) {
return request({
url: 'api/features/CuteDynamicTable/searchMenu',
method: 'post',
data: query
})
}
export default { searchMenu }
@@ -37,6 +37,7 @@
>
<el-table-column v-if="showSelect" type="selection" width="55" />
<slot />
</el-table>
<el-pagination
v-if="paging"
:current-page="pageProps.current"
@@ -47,7 +48,7 @@
@size-change="(size) => crud.onPageChange(pageProps.current, size, pageProps.total)"
@current-change="(current) => crud.onPageChange(current, pageProps.pageSize, pageProps.total)"
/>
</el-table></div>
</div>
</template>
<script>
@@ -145,18 +146,14 @@ export default {
try {
this.crud.loading = true
// 请求远程数据
const response = await this.fetch(params)
// console.error('response', response)
// { content: [], totalElements: 0 }
let transformData = await this.fetch(params)
// 转换为表格所需要的数据
if (this.responseTransform) {
return this.responseTransform(response)
transformData = this.responseTransform(transformData)
}
if (response && response.hasOwnProperty('totalElements') && response.hasOwnProperty('content')) {
this.pageProps.total = response.totalElements
this.crud.dataSource = response.content
}
return response
// if (response && response.hasOwnProperty('totalElements') && response.hasOwnProperty('content')) {
this.pageProps.total = transformData.totalElements
this.crud.dataSource = transformData.content
} catch (e) {
console.error('CuteDragTable请求远程数据异常', e)
this.pageProps.total = 0
@@ -152,18 +152,14 @@ export default {
try {
this.crud.loading = true
// 请求远程数据
const response = await this.fetch(params)
// console.error('response', response)
// { content: [], totalElements: 0 }
let transformData = await this.fetch(params)
// 转换为表格所需要的数据
if (this.responseTransform) {
return this.responseTransform(response)
transformData = this.responseTransform(transformData)
}
if (response && response.hasOwnProperty('totalElements') && response.hasOwnProperty('content')) {
this.pageProps.total = response.totalElements
this.crud.dataSource = response.content
}
return response
// if (response && response.hasOwnProperty('totalElements') && response.hasOwnProperty('content')) {
this.pageProps.total = transformData.totalElements
this.crud.dataSource = transformData.content
} catch (e) {
console.error('CuteSimpleTable请求远程数据异常', e)
this.pageProps.total = 0
@@ -74,7 +74,7 @@ export default {
},
curd: {
paramsTransform: (pageProps) => {
const values = this.form.model
const values = this.form
return {
page: pageProps.current,
size: pageProps.pageSize,
@@ -0,0 +1,140 @@
<template>
<div>
<h4>何时使用</h4>
<ul class="description">
<li>展示结构化数据列表,并支持排序、分页、拖拽排序</li>
<li>在使用过程中有任何问题,咨询 @Odboy(前端)</li>
</ul>
<h4>基础用法</h4>
<!-- 表格渲染 -->
<!-- fetch: 获取远程数据 -->
<!-- params-transform: 组装查询参数 -->
<!-- responseTransform: 组装表格对象。对响应结果做处理 -->
<!-- showSelect: 是否多选。不传默认false,传true为多选 -->
<!-- @selection-change: 当且仅当mode为multi时启用 -->
<!-- @order-change: 当排序字段被单击,el-table-column 需添加 sortable="custom" 属性 -->
<cute-dynamic-table
ref="instance"
:fetch="curd.fetch"
:params-transform="curd.paramsTransform"
:page-props="curd.pageProps"
show-select
>
<template v-slot:batchArea>
<cute-button type="primary">批量绑定</cute-button>
</template>
<template v-slot:toolArea>
<cute-button type="primary">导出</cute-button>
</template>
<template v-slot:operation>
<el-table-column label="操作" width="150" min-width="150" fixed="right">
<template v-slot="scope">
<div>
<el-button type="text" @click="onTableEditClick(scope.row)">编辑</el-button>
<el-button type="text" @click="onTableDeleteClick(scope.row)">删除</el-button>
</div>
</template>
</el-table-column>
</template>
</cute-dynamic-table>
<h4>API</h4>
<el-table :data="apiData">
<el-table-column prop="name" label="参数" width="220" />
<el-table-column prop="remark" label="说明" width="450" />
<el-table-column prop="type" label="类型" />
<el-table-column prop="defaultValue" label="默认值" />
<el-table-column prop="required" label="是否必填" />
</el-table>
<h4>方法</h4>
<el-table :data="methodData">
<el-table-column prop="name" label="函数" width="220" />
<el-table-column prop="remark" label="说明" width="450" />
<el-table-column prop="inputArgs" label="入参" />
<el-table-column prop="outArgs" label="出参" />
</el-table>
</div>
</template>
<script>
import FeatureCuteDynamicTableService from '@/api/features/cute-dynamic-table'
import CuteButton from '@/views/components/dev/CuteButton.vue'
import { FormatRowDateTimeStr } from '@/utils/KitUtil'
import CuteDynamicTable from '@/views/components/advanced/CuteDynamicTable.vue'
export default {
name: 'CuteDynamicTableDemo',
components: { CuteDynamicTable, CuteButton },
data() {
return {
form: {
blurry: ''
},
curd: {
paramsTransform: (pageProps) => {
const values = this.form
return {
page: pageProps.current,
size: pageProps.pageSize,
args: {
...values
}
}
},
fetch: async(queryParams) => {
return FeatureCuteDynamicTableService.searchMenu(queryParams)
},
columns: [
{ prop: 'name', label: '名称' },
{ prop: 'description', label: '描述' },
{ prop: 'createTime', label: '创建时间', formatter: FormatRowDateTimeStr },
{ prop: 'createBy', label: '创建人' }
],
pageProps: {
current: 1,
pageSize: 10,
total: 0
}
},
apiData: [
{ name: 'primary-key', remark: '对象中的哪个字段设置为主键', type: 'string', defaultValue: 'id', required: '否' },
{ name: 'fetch', remark: '请求数据的API接口', type: 'async(queryParams) => {}', defaultValue: '-', required: '否' },
{ name: 'paramsTransform', remark: '组装请求参数的方法', type: '(pageProps) => {}', defaultValue: '-', required: '否' },
{ name: 'responseTransform', remark: '组装响应结果的方法', type: '(response) => {}', defaultValue: '-', required: '否' },
{ name: 'showSelect', remark: '是否支持多选', type: 'boolean', defaultValue: 'false', required: '否' },
{ name: 'paging', remark: '是否显示分页组件', type: 'boolean', defaultValue: 'true', required: '否' },
{ name: 'pageProps', remark: '分页参数', type: 'object', defaultValue: '{current: 1,pageSize: 10,total: 0}', required: '否' },
{ name: 'customHeight', remark: '自定义高度', type: 'number', defaultValue: 'null', required: '否' },
{ name: 'selection-change', remark: '选中列表项发生改变的时候触发的回调', type: '(array) => {}', defaultValue: '-', required: '否' },
{ name: 'order-change', remark: '排序列发生改变的时候触发的回调。el-table-column 需添加 sortable="custom" 属性', type: '(column, orderType) => {}', defaultValue: '-', required: '否' },
{ name: 'page-change', remark: '分页数据发生改变的时候触发的回调', type: '(currentPage, pageSize) => {}', defaultValue: '-', required: '否' }
],
methodData: [
{ name: 'getDataSource', remark: '获取当前表格的数据', inputArgs: '-', outArgs: 'array' },
{ name: 'refresh', remark: '刷新当前表格的数据,可以理解为重新执行查询方法。', inputArgs: '-', outArgs: '-' }
]
}
},
mounted() {
this.refreshData()
},
methods: {
FormatRowDateTimeStr,
refreshData() {
this.$refs.instance.refresh()
},
onTableEditClick(row) {
console.log('编辑', row)
},
onTableDeleteClick(row) {
console.log('删除', row)
}
}
}
</script>
<style lang="scss" scoped>
ul {
padding-left: 20px;
}
.description > li{
font-size: 12px;
}
</style>
@@ -74,7 +74,7 @@ export default {
},
curd: {
paramsTransform: (pageProps) => {
const values = this.form.model
const values = this.form
return {
page: pageProps.current,
size: pageProps.pageSize,
@@ -86,12 +86,6 @@ export default {
fetch: async(queryParams) => {
return DictService.searchDict(queryParams)
},
columns: [
{ prop: 'name', label: '名称' },
{ prop: 'description', label: '描述' },
{ prop: 'createTime', label: '创建时间', formatter: FormatRowDateTimeStr },
{ prop: 'createBy', label: '创建人' }
],
pageProps: {
current: 1,
pageSize: 10,
@@ -0,0 +1,71 @@
/*
* Copyright 2021-2026 Odboy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.odboy.system.features;
import cn.hutool.core.util.StrUtil;
import cn.odboy.base.KitPageArgs;
import cn.odboy.system.features.core.KitDynamicTableResponse;
import cn.odboy.system.features.model.SystemMenuDynamicTableModel;
import cn.odboy.system.dal.dataobject.SystemMenuTb;
import cn.odboy.system.dal.model.request.SystemQueryMenuArgs;
import cn.odboy.system.dal.mysql.SystemMenuMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = "系统组件:CuteDynamicTable演示")
@RequestMapping("/api/features/CuteDynamicTable")
public class CuteDynamicTableDemoApi {
@Autowired
private SystemMenuMapper systemMenuMapper;
@ApiOperation("查询动态数据")
@PostMapping(value = "/searchMenu")
@PreAuthorize("@el.check()")
public ResponseEntity<KitDynamicTableResponse<SystemMenuDynamicTableModel>> searchMenu(@Validated @RequestBody KitPageArgs<SystemQueryMenuArgs> pageArgs) {
// 请求参数
Integer page = pageArgs.getPage();
Integer size = pageArgs.getSize();
KitPageArgs.OrderBy orderBy = pageArgs.getOrderBy();
SystemQueryMenuArgs args = pageArgs.getArgs();
// 分页查询
QueryWrapper<SystemMenuTb> wrapper = new QueryWrapper<>();
if (orderBy != null) {
orderBy.bindWrapper(wrapper);
}
IPage<SystemMenuTb> iPage = new Page<>(page, size);
LambdaQueryWrapper<SystemMenuTb> lambda = wrapper.lambda();
if (args != null) {
lambda.like(StrUtil.isNotBlank(args.getBlurry()), SystemMenuTb::getTitle, args.getBlurry());
}
IPage<SystemMenuTb> pageResult = systemMenuMapper.selectPage(iPage, wrapper);
// 响应结果
return ResponseEntity.ok(new KitDynamicTableResponse<>(SystemMenuDynamicTableModel.class, "id", pageResult));
}
}
@@ -0,0 +1,39 @@
/*
* Copyright 2021-2026 Odboy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.odboy.system.features.core;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
public @interface KitDynamicTableColumn {
/**
* 标题
*/
String value() default "";
/**
* 宽度
*/
int width() default 0;
/**
* 是否排序字段
*/
boolean sortable() default false;
}
@@ -0,0 +1,131 @@
/*
* Copyright 2021-2026 Odboy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.odboy.system.features.core;
import cn.hutool.core.util.ReflectUtil;
import cn.odboy.base.KitObject;
import cn.odboy.system.features.model.SystemMenuDynamicTableModel;
import cn.odboy.system.dal.dataobject.SystemMenuTb;
import cn.odboy.util.KitBeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* 动态表格
*
* @author odboy
* @date 2026-02-05
*/
@Getter
public class KitDynamicTableResponse<T> extends KitObject {
/**
* 主键
*/
@Setter
private String primaryKey = "id";
/**
* 表格列定义
*/
private List<Column> columns = new ArrayList<>();
/**
* 数据总数
*/
private Long totalElements;
/**
* 数据内容
*/
private List<T> content;
public KitDynamicTableResponse(Class<T> clazz, IPage<SystemMenuTb> pageResult) {
this.renderColumns(clazz);
this.setPage(clazz, pageResult);
}
public KitDynamicTableResponse(Class<T> clazz, String id, IPage<SystemMenuTb> pageResult) {
this.primaryKey = id;
this.renderColumns(clazz);
this.setPage(clazz, pageResult);
}
private void renderColumns(Class<T> clazz) {
List<Column> columns = new ArrayList<>();
if (clazz == null) {
this.columns = columns;
return;
}
Field[] fields = ReflectUtil.getFields(clazz);
for (Field field : fields) {
if ("serialVersionUID".equals(field.getName())) {
continue;
}
Column column = new Column();
column.setName(field.getName());
KitDynamicTableColumn annotation = field.getAnnotation(KitDynamicTableColumn.class);
if (annotation == null) {
column.setTitle(field.getName());
column.setWidth(null);
} else {
column.setTitle(annotation.value());
column.setWidth(annotation.width() == 0 ? null : annotation.width());
column.setSortable(annotation.sortable());
}
columns.add(column);
}
this.columns = columns;
}
public void setPage(Class<T> clazz, IPage<SystemMenuTb> pageResult) {
if (pageResult == null) {
return;
}
this.totalElements = pageResult.getTotal();
this.content = KitBeanUtil.copyToList(pageResult.getRecords(), clazz);
}
@Getter
@Setter
public static class Column {
/**
* 索引名称
*/
private String name;
/**
* 索引标题
*/
private String title;
/**
* 表格宽度
*/
private Integer width;
/**
* 是否排序列
*/
private Boolean sortable = false;
}
public static void main(String[] args) {
KitDynamicTableResponse<SystemMenuDynamicTableModel> response = new KitDynamicTableResponse<>(SystemMenuDynamicTableModel.class, "id", new Page<>());
System.err.println(response);
}
}
@@ -0,0 +1,55 @@
/*
* Copyright 2021-2026 Odboy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.odboy.system.features.model;
import cn.odboy.base.KitObject;
import cn.odboy.system.features.core.KitDynamicTableColumn;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SystemMenuDynamicTableModel extends KitObject {
@KitDynamicTableColumn(value = "ID")
private Long id;
@KitDynamicTableColumn(value = "菜单标题")
private String title;
@KitDynamicTableColumn(value = "菜单组件名称")
private String componentName;
@KitDynamicTableColumn(value = "排序")
private Integer menuSort = 999;
@KitDynamicTableColumn(value = "组件路径", width = 240)
private String component;
@KitDynamicTableColumn(value = "路由地址", width = 120)
private String path;
@KitDynamicTableColumn(value = "菜单类型")
private Integer type;
@KitDynamicTableColumn(value = "权限标识")
private String permission;
@KitDynamicTableColumn(value = "菜单图标")
private String icon;
@KitDynamicTableColumn(value = "缓存")
private Boolean cache;
@KitDynamicTableColumn(value = "是否隐藏")
private Boolean hidden;
@KitDynamicTableColumn(value = "上级菜单")
private Long pid;
@KitDynamicTableColumn(value = "子节点数目", sortable = true)
private Integer subCount = 0;
@KitDynamicTableColumn(value = "外链菜单")
private Boolean iFrame;
}