Skip to content

Commit

Permalink
fix(components): [dynamic-table] initial fetchData did not carry the …
Browse files Browse the repository at this point in the history
…default value
  • Loading branch information
buqiyuan committed Aug 31, 2022
1 parent 03e7806 commit c2a31d4
Show file tree
Hide file tree
Showing 10 changed files with 187 additions and 136 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@
"@types/lodash-es": "~4.17.6",
"@types/node": "~18.7.14",
"@types/webpack-env": "~1.18.0",
"@typescript-eslint/eslint-plugin": "~5.36.0",
"@typescript-eslint/parser": "~5.36.0",
"@typescript-eslint/eslint-plugin": "~5.36.1",
"@typescript-eslint/parser": "~5.36.1",
"@vue/cli-plugin-babel": "~5.0.8",
"@vue/cli-plugin-eslint": "~5.0.8",
"@vue/cli-plugin-router": "~5.0.8",
Expand Down Expand Up @@ -103,7 +103,7 @@
"unplugin-vue-define-options": "~0.7.3",
"vue-cli-plugin-windicss": "~1.1.6",
"vue-eslint-parser": "~9.0.3",
"vue-tsc": "^0.40.4"
"vue-tsc": "^0.40.5"
},
"__npminstall_done": false,
"repository": {
Expand Down
5 changes: 2 additions & 3 deletions src/components/core/dynamic-table/src/dynamic-table.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
</ToolBar>
<SchemaForm
ref="editTableFormRef"
layout="inline"
no-style
:initial-values="editFormModel"
:show-action-button-group="false"
Expand All @@ -38,7 +37,7 @@
<Table
ref="tableRef"
v-bind="getBindValues"
:columns="getColumns"
:columns="innerColumns"
:data-source="tableData"
@change="handleTableChange"
>
Expand Down Expand Up @@ -98,7 +97,7 @@
};
// 表格列的配置描述
const { getColumns } = useColumns({
const { innerColumns } = useColumns({
props,
slots,
state: tableState,
Expand Down
9 changes: 5 additions & 4 deletions src/components/core/dynamic-table/src/hooks/useColumns.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { computed, unref, useSlots } from 'vue';
import { ref, watchEffect, unref, useSlots } from 'vue';
import { cloneDeep, isFunction, mergeWith } from 'lodash-es';
import { EditableCell } from '../components/';
import { ColumnKeyFlag, CustomRenderParams } from '../types/column';
Expand All @@ -24,11 +24,12 @@ export type UseTableColumnsContext = {

export const useColumns = ({ state, methods, props, tableAction }: UseTableColumnsContext) => {
const slots = useSlots();
const innerColumns = ref(props.columns);
const { getColumnKey } = methods;
const { getProps } = state;
const { isEditable } = tableAction;

const getColumns = computed<TableColumn<any>[]>(() => {
watchEffect(() => {
const innerProps = { ...unref(getProps) };
const ColumnKeyFlags = Object.keys(ColumnKeyFlag);
const columns = cloneDeep(innerProps!.columns!.filter((n) => !n.hideInTable));
Expand All @@ -53,7 +54,7 @@ export const useColumns = ({ state, methods, props, tableAction }: UseTableColum
} as TableColumn);
}

return columns.map((item) => {
innerColumns.value = columns.map((item) => {
const customRender = item.customRender;

const rowKey = props.rowKey as string;
Expand Down Expand Up @@ -149,6 +150,6 @@ export const useColumns = ({ state, methods, props, tableAction }: UseTableColum
};

return {
getColumns,
innerColumns,
};
};
64 changes: 33 additions & 31 deletions src/components/core/dynamic-table/src/hooks/useEditable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { cloneDeep } from 'lodash-es';
import { message } from 'ant-design-vue';
import type { DynamicTableProps } from '../dynamic-table';
import type { TableState } from './useTableState';
import type { TableColumn } from '@/components/core/dynamic-table/src/types/column';

type UseTableMethodsContext = {
state: TableState;
Expand Down Expand Up @@ -40,6 +41,34 @@ export const useEditable = ({ state, props }: UseTableMethodsContext) => {
});
};

/** 获取要编辑的值 */
const getEditValue = (
recordKey: Key,
currentRow?: Recordable,
columns?: TableColumn<Recordable<any>>[],
) => {
// 克隆当前行数据作为临时编辑的表单数据,避免直接修改原数据
const editValue = cloneDeep(
currentRow ?? tableData.value.find((n) => n[String(props.rowKey)] === recordKey),
);
// 用户设置的默认值优先
columns?.forEach((item) => {
const { formItemProps, editFormItemProps } = item;
const field = (item.dataIndex || item.key) as string;
if (
!Object.is(editFormItemProps?.extendSearchFormProps, false) &&
formItemProps &&
Reflect.has(formItemProps, 'defaultValue')
) {
editValue[field] = formItemProps.defaultValue;
}
if (editFormItemProps && Reflect.has(editFormItemProps, 'defaultValue')) {
editValue[field] = editFormItemProps.defaultValue;
}
});
return editValue;
};

/**
* @description 进入编辑行状态
*
Expand All @@ -54,20 +83,7 @@ export const useEditable = ({ state, props }: UseTableMethodsContext) => {
message.warn(props.onlyOneLineEditorAlertMessage || '只能同时编辑一行');
return false;
}
// 克隆当前行数据作为临时编辑的表单数据,避免直接修改原数据
const editValue = cloneDeep(
currentRow ?? tableData.value.find((n) => n[String(props.rowKey)] === recordKey),
);
// 用户设置的默认值优先
props.columns.forEach((item) => {
const field = (item.dataIndex || item.key) as string;
if (item.formItemProps && Reflect.has(item.formItemProps, 'defaultValue')) {
editValue[field] = item.formItemProps.defaultValue;
}
if (item.editFormItemProps && Reflect.has(item.editFormItemProps, 'defaultValue')) {
editValue[field] = item.editFormItemProps.defaultValue;
}
});
const editValue = getEditValue(recordKey, currentRow, props.columns);
setEditFormModel(recordKey, editValue);
editableRowKeys.value.add(recordKey);
return true;
Expand All @@ -76,23 +92,9 @@ export const useEditable = ({ state, props }: UseTableMethodsContext) => {
/** 进入编辑单元格状态 */
const startCellEditable = (recordKey: Key, dataIndex: Key, currentRow?: Recordable) => {
editableRowKeys.value.clear();
// 克隆当前行数据作为临时编辑的表单数据,避免直接修改原数据
const editValue = cloneDeep(
currentRow ?? tableData.value.find((n) => n[String(props.rowKey)] === recordKey),
);
const targetColumn = props.columns.find((n) => n.dataIndex === dataIndex);
if (targetColumn) {
const field = (targetColumn.dataIndex || targetColumn.key) as string;
if (targetColumn.formItemProps && Reflect.has(targetColumn.formItemProps, 'defaultValue')) {
editValue[field] = targetColumn.formItemProps.defaultValue;
}
if (
targetColumn.editFormItemProps &&
Reflect.has(targetColumn.editFormItemProps, 'defaultValue')
) {
editValue[field] = targetColumn.editFormItemProps.defaultValue;
}
}
const targetColumn = props.columns.filter((n) => n.dataIndex === dataIndex);
const editValue = getEditValue(recordKey, currentRow, targetColumn);

editableCellKeys.value.add(`${recordKey}.${dataIndex}`);
setEditFormModel(recordKey, {
...(getEditFormModel(recordKey) || editValue),
Expand Down
48 changes: 36 additions & 12 deletions src/components/core/dynamic-table/src/hooks/useTableMethods.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { unref } from 'vue';
import { unref, nextTick } from 'vue';
import { isObject, isFunction } from 'lodash-es';
import { useEditable } from './useEditable';
import type { DynamicTableProps, DynamicTableEmitFn } from '../dynamic-table';
import type { OnChangeCallbackParams, TableColumn } from '../types/';
import type { TableState } from './useTableState';
import { isAsyncFunction } from '@/utils/is';
import type { Pagination, TableState } from './useTableState';
import { isAsyncFunction, isBoolean } from '@/utils/is';

export type TableMethods = ReturnType<typeof useTableMethods>;

Expand Down Expand Up @@ -40,11 +40,20 @@ export const useTableMethods = ({ state, props, emit }: UseTableMethodsContext)
* @description 获取表格数据
*/
const fetchData = async (params = {}, rest?: OnChangeCallbackParams) => {
const [pagination] = rest || [];
// 如果用户没有提供dataSource并且dataRequest是一个函数,那就进行接口请求
if (
Object.is(props.dataSource, undefined) &&
(isFunction(props.dataRequest) || isAsyncFunction(props.dataRequest))
) {
await nextTick();
if (queryFormRef.value) {
const values = await queryFormRef.value.validate();
params = {
...queryFormRef.value.handleFormValues(values),
...params,
};
}
const _pagination = unref(paginationRef)!;
// 是否启用了分页
const enablePagination = isObject(_pagination);
Expand Down Expand Up @@ -74,11 +83,13 @@ export const useTableMethods = ({ state, props, emit }: UseTableMethodsContext)
}
}

Object.assign(unref(paginationRef), {
current: ~~page,
pageSize: ~~size,
total: ~~total,
updatePagination({
current: page,
pageSize: size,
total,
});
} else {
updatePagination(pagination);
}
if (Array.isArray(data?.list)) {
tableData.value = data!.list;
Expand All @@ -87,7 +98,10 @@ export const useTableMethods = ({ state, props, emit }: UseTableMethodsContext)
} else {
tableData.value = [];
}
} else {
updatePagination(pagination);
}

retryFetchCount = 2;
return tableData;
};
Expand All @@ -109,13 +123,11 @@ export const useTableMethods = ({ state, props, emit }: UseTableMethodsContext)
const handleTableChange = async (...rest: OnChangeCallbackParams) => {
// const [pagination, filters, sorter] = rest;
const [pagination] = rest;
let params = {};
if (queryFormRef.value) {
const values = await queryFormRef.value.validate();
params = queryFormRef.value.handleFormValues(values);
await queryFormRef.value.validate();
}
Object.assign(unref(paginationRef), pagination || {});
fetchData(params, rest);
updatePagination(pagination);
await fetchData({}, rest);
emit('change', ...rest);
};

Expand All @@ -137,6 +149,18 @@ export const useTableMethods = ({ state, props, emit }: UseTableMethodsContext)
}
};

/** 更新表格分页信息 */
const updatePagination = (info: Pagination = paginationRef.value) => {
if (isBoolean(info)) {
paginationRef.value = info;
} else if (isObject(paginationRef.value)) {
paginationRef.value = {
...paginationRef.value,
...info,
};
}
};

/**
* @description当外部需要动态改变搜索表单的值或选项时,需要调用此方法获取dynamicFormRef实例
*/
Expand Down
6 changes: 6 additions & 0 deletions src/views/demos/tables/edit-row-table/columns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export const columns: TableColumn<ListItemType>[] = [
return index > 0;
},
formItemProps: {
defaultValue: '李白',
rules: [{ required: true, message: '请输入姓名' }],
},
editFormItemProps: {
/** 不继承于 `formItemProps`的属性 */
extendSearchFormProps: false,
rules: [{ required: true, message: '请输入姓名' }],
},
},
Expand Down
3 changes: 2 additions & 1 deletion src/views/demos/tables/edit-row-table/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,13 @@
const [DynamicTable] = useTable();
const editableType = ref<EditableType>('single');
const editableType = ref<EditableType>('cell');
const loadData = async (
params,
onChangeParams: OnChangeCallbackParams,
): Promise<API.TableListResult> => {
console.log('params', params);
console.log('onChangeParams', onChangeParams);
await waitTime(500);
Expand Down
5 changes: 5 additions & 0 deletions src/views/demos/tables/search-table/columns.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,19 @@ export const columns: TableColumn<ListItemType>[] = [
align: 'center',
dataIndex: 'name',
sorter: true,
width: 300,
resizable: true,
formItemProps: {
defaultValue: '李白',
required: true,
},
},
{
title: '性别',
align: 'center',
dataIndex: 'gender',
width: 120,
resizable: true,
formItemProps: {
component: 'Select',
componentProps: ({ formInstance, formModel, tableInstance }) => ({
Expand Down
15 changes: 14 additions & 1 deletion src/views/demos/tables/search-table/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,14 @@
<template #description> 查询表格-查询表单使用示例 </template>
</Alert>
<Card title="查询表单基本使用示例" style="margin-top: 20px">
<DynamicTable size="small" bordered :data-request="loadData" :columns="columns" row-key="id">
<DynamicTable
size="small"
bordered
:data-request="loadData"
:columns="columns"
row-key="id"
@resize-column="handleResizeColumn"
>
<template #bodyCell="{ column, record }">
<template v-if="column.dataIndex === 'name'">
{{ record.name }} <a class="text-red-500">[测试bodyCell]</a>
Expand All @@ -26,6 +33,7 @@
params,
onChangeParams: OnChangeCallbackParams,
): Promise<API.TableListResult> => {
console.log('params', params);
console.log('onChangeParams', onChangeParams);
return new Promise((resolve) => {
Expand Down Expand Up @@ -55,6 +63,11 @@
}, 500);
});
};
const handleResizeColumn = (w, col) => {
// console.log('w', w, col);
col.width = w;
};
</script>

<style lang="less" scoped></style>
Loading

1 comment on commit c2a31d4

@vercel
Copy link

@vercel vercel bot commented on c2a31d4 Aug 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

vue3-antd-admin – ./

vue3-antd-admin.vercel.app
vue3-antd-admin-buqiyuan.vercel.app
vue3-antd-admin-git-main-buqiyuan.vercel.app

Please sign in to comment.