fix: 修复列表搜索翻页后丢失搜索条件的bug

This commit is contained in:
gaoyunqi
2024-09-09 11:20:06 +08:00
parent 6b6e7ad0a6
commit 78b05fc000
2 changed files with 944 additions and 965 deletions

View File

@ -1,20 +1,15 @@
<template>
<div ref="wrapRef" :class="getWrapperClass">
<div
:style="{
height: '100%',
background: '#fff',
}"
>
<div :style="{height: '100%',background: '#fff'}">
<a-table
ref="tableElRef"
v-bind="getBindValues"
:rowClassName="getRowClassName"
v-show="getEmptyDataIsShowTable"
ref="tableElRef"
:rowClassName="getRowClassName"
:showSorterTooltip="false"
v-bind="getBindValues"
@change="handleTableChange"
>
<template #summary v-if="columns.filter((x) => x.total).length > 0">
<template v-if="columns.filter((x) => x.total).length > 0" #summary>
<a-table-summary-row>
<a-table-summary-cell>合计</a-table-summary-cell>
<a-table-summary-cell v-if="getBindValues.rowSelection" />
@ -36,7 +31,7 @@
<a-table-summary-cell v-if="getBindValues.actionColumn" />
</a-table-summary-row>
</template>
<template #[item]="data" v-for="item in Object.keys($slots)" :key="item">
<template v-for="item in Object.keys($slots)" :key="item" #[item]="data">
<slot :name="item" v-bind="data || {}"></slot>
</template>
@ -53,36 +48,6 @@
<template #headerCell="{ column }">
<HeaderCell :column="column" />
</template>
<!-- <template #emptyText>
<div class="ant-empty-image">
<svg class="ant-empty-img-simple" width="64" height="20" viewBox="0 0 64 20">
<g transform="translate(0 1)" fill="none" fill-rule="evenodd">
<ellipse
class="ant-empty-img-simple-ellipse"
fill="#F5F5F5"
cx="32"
cy="33"
rx="32"
ry="7"
/>
<g class="ant-empty-img-simple-g" fill-rule="nonzero" stroke="#D9D9D9">
<path
d="M55 12.76L44.854 1.258C44.367.474 43.656 0 42.907 0H21.093c-.749 0-1.46.474-1.947 1.257L9 12.761V22h46v-9.24z"
/>
<path
d="M41.613 15.931c0-1.605.994-2.93 2.227-2.931H55v18.137C55 33.26 53.68 35 52.05 35h-40.1C10.32 35 9 33.259 9 31.137V13h11.16c1.233 0 2.227 1.323 2.227 2.928v.022c0 1.605 1.005 2.901 2.237 2.901h14.752c1.232 0 2.237-1.308 2.237-2.913v-.007z"
fill="#FAFAFA"
class="ant-empty-img-simple-path"
/>
</g>
</g>
</svg>
</div>
<p>{{ t('暂无数据') }}</p>
</template> -->
<!-- <template #[`header-${column.dataIndex}`] v-for="(column, index) in columns" :key="index">-->
<!-- <HeaderCell :column="column" />-->
<!-- </template>-->
</a-table>
</div>
</div>
@ -92,8 +57,8 @@
BasicTableProps,
TableActionType,
SizeType,
ColumnChangeParam,
} from './types/table';
ColumnChangeParam
} from "./types/table";
import {
defineComponent,
@ -104,56 +69,56 @@
inject,
watchEffect,
onMounted,
nextTick,
} from 'vue';
import { useForm } from '/@/components/Form/index';
import { PageWrapperFixedHeightKey } from '/@/components/Page';
import HeaderCell from './components/HeaderCell.vue';
import { InnerHandlers } from './types/table';
import { usePagination } from './hooks/usePagination';
import { useColumns } from './hooks/useColumns';
import { useDataSource } from './hooks/useDataSource';
import { useLoading } from './hooks/useLoading';
import { useRowSelection } from './hooks/useRowSelection';
import { useTableScroll } from './hooks/useTableScroll';
import { useTableScrollTo } from './hooks/useScrollTo';
import { useCustomRow } from './hooks/useCustomRow';
import { useTableStyle } from './hooks/useTableStyle';
import { useTableHeader } from './hooks/useTableHeader';
import { useTableExpand } from './hooks/useTableExpand';
import { createTableContext } from './hooks/useTableContext';
import { useTableFooter } from './hooks/useTableFooter';
import { useTableForm } from './hooks/useTableForm';
import { useDesign } from '/@/hooks/web/useDesign';
nextTick
} from "vue";
import { useForm } from "/@/components/Form/index";
import { PageWrapperFixedHeightKey } from "/@/components/Page";
import HeaderCell from "./components/HeaderCell.vue";
import { InnerHandlers } from "./types/table";
import { usePagination } from "./hooks/usePagination";
import { useColumns } from "./hooks/useColumns";
import { useDataSource } from "./hooks/useDataSource";
import { useLoading } from "./hooks/useLoading";
import { useRowSelection } from "./hooks/useRowSelection";
import { useTableScroll } from "./hooks/useTableScroll";
import { useTableScrollTo } from "./hooks/useScrollTo";
import { useCustomRow } from "./hooks/useCustomRow";
import { useTableStyle } from "./hooks/useTableStyle";
import { useTableHeader } from "./hooks/useTableHeader";
import { useTableExpand } from "./hooks/useTableExpand";
import { createTableContext } from "./hooks/useTableContext";
import { useTableFooter } from "./hooks/useTableFooter";
import { useTableForm } from "./hooks/useTableForm";
import { useDesign } from "/@/hooks/web/useDesign";
import { omit, sum } from 'lodash-es';
import { basicProps } from './props';
import { isFunction } from '/@/utils/is';
import { warn } from '/@/utils/log';
import { useI18n } from '/@/hooks/web/useI18n';
import { omit, sum } from "lodash-es";
import { basicProps } from "./props";
import { isFunction } from "/@/utils/is";
import { warn } from "/@/utils/log";
import { useI18n } from "/@/hooks/web/useI18n";
export default defineComponent({
components: {
HeaderCell,
HeaderCell
},
props: basicProps,
emits: [
'fetch-success',
'fetch-error',
'selection-change',
'register',
'row-click',
'row-dbClick',
'row-contextmenu',
'row-mouseenter',
'row-mouseleave',
'edit-end',
'edit-cancel',
'edit-row-end',
'edit-change',
'expanded-rows-change',
'change',
'columns-change',
"fetch-success",
"fetch-error",
"selection-change",
"register",
"row-click",
"row-dbClick",
"row-contextmenu",
"row-mouseenter",
"row-mouseleave",
"edit-end",
"edit-cancel",
"edit-row-end",
"edit-change",
"expanded-rows-change",
"change",
"columns-change"
],
setup(props, { attrs, emit, slots, expose }) {
const { t } = useI18n();
@ -162,7 +127,7 @@
const wrapRef = ref(null);
const formRef = ref();
const innerPropsRef = ref<Partial<BasicTableProps>>();
const { prefixCls } = useDesign('basic-table');
const { prefixCls } = useDesign("basic-table");
const [registerForm, formActions] = useForm();
const getProps = computed(() => {
@ -174,7 +139,7 @@
unref(isFixedHeightPage) &&
props.canResize &&
warn(
"'canResize' of BasicTable may not work in PageWrapper with 'fixedHeight' (especially in hot updates)",
"'canResize' of BasicTable may not work in PageWrapper with 'fixedHeight' (especially in hot updates)"
);
});
@ -184,7 +149,7 @@
getPagination,
setPagination,
setShowPagination,
getShowPagination,
getShowPagination
} = usePagination(getProps);
const {
@ -194,7 +159,7 @@
clearSelectedRowKeys,
getSelectRowKeys,
deleteSelectRowByKey,
setSelectedRowKeys,
setSelectedRowKeys
} = useRowSelection(getProps, tableData, emit);
const {
@ -212,6 +177,7 @@
reload,
getAutoCreateKey,
updateTableData,
setSearchFormData
} = useDataSource(
getProps,
{
@ -220,17 +186,17 @@
setLoading,
setPagination,
getFieldsValue: formActions.getFieldsValue,
clearSelectedRowKeys,
clearSelectedRowKeys
},
emit,
emit
);
function handleTableChange(...args) {
const { onChange, isPaginateByDataSource, isFilterByDataSoure } = unref(getProps);
if (args[3].action === 'filter' && isFilterByDataSoure) return;
if (args[3].action === "filter" && isFilterByDataSoure) return;
onTableChange.call(undefined, isPaginateByDataSource, ...args);
emit('change', ...args);
emit("change", ...args);
// 解决通过useTable注册onChange时不起作用的问题
onChange && isFunction(onChange) && onChange.call(undefined, ...args);
@ -242,7 +208,7 @@
setCacheColumnsByField,
setColumns,
getColumnsRef,
getCacheColumns,
getCacheColumns
} = useColumns(getProps, getPaginationInfo);
const { getScrollRef, redoHeight, tabelWidth } = useTableScroll(
@ -252,7 +218,7 @@
getRowSelectionRef,
getDataSourceRef,
wrapRef,
formRef,
formRef
);
const { scrollTo } = useTableScrollTo(tableElRef, getDataSourceRef);
@ -262,7 +228,7 @@
getSelectRowKeys,
clearSelectedRowKeys,
getAutoCreateKey,
emit,
emit
});
const { getRowClassName } = useTableStyle(getProps, prefixCls);
@ -270,16 +236,16 @@
const { getExpandOption, expandAll, expandRows, collapseAll } = useTableExpand(
getProps,
tableData,
emit,
emit
);
const calcToolBarWidth = ref(0);
const handlers: InnerHandlers = {
onColumnsChange: (data: ColumnChangeParam[]) => {
emit('columns-change', data);
emit("columns-change", data);
// support useTable
unref(getProps).onColumnsChange?.(data);
},
}
};
const { getFormProps, replaceFormSlotKey, getFormSlotKeys, handleSearchInfoChange } =
@ -294,20 +260,20 @@
...unref(getHeaderProps),
scroll: unref(getScrollRef),
loading: unref(getLoading),
tableLayout: 'fixed',
tableLayout: "fixed",
rowSelection: unref(getRowSelectionRef),
rowKey: unref(getRowKey),
columns: toRaw(unref(getViewColumns)),
pagination: toRaw(unref(getPaginationInfo)),
dataSource,
footer: unref(getFooterProps),
...unref(getExpandOption),
...unref(getExpandOption)
};
if (slots.expandedRowRender) {
propsData = omit(propsData, 'scroll');
propsData = omit(propsData, "scroll");
}
propsData = omit(propsData, ['class', 'onChange']);
propsData = omit(propsData, ["class", "onChange"]);
return propsData;
});
@ -315,21 +281,21 @@
getProps,
getScrollRef,
tableElRef,
getDataSourceRef,
getDataSourceRef
);
const getWrapperClass = computed(() => {
const values = unref(getBindValues);
let page = getShowPagination() ? prefixCls + '-form-has-pagenation' : '';
let page = getShowPagination() ? prefixCls + "-form-has-pagenation" : "";
return [
prefixCls,
attrs.class,
{
[`${prefixCls}-form-container`]: values.useSearchForm,
[`${prefixCls}--inset`]: values.inset,
[`${prefixCls}--inset`]: values.inset
},
page,
page
];
});
@ -344,10 +310,11 @@
function setProps(props: Partial<BasicTableProps>) {
innerPropsRef.value = { ...unref(innerPropsRef), ...props };
}
const setToolBarWidth = () => {
if (!tableElRef.value) return;
calcToolBarWidth.value = tableElRef.value?.$el.querySelector(
'.vben-basic-table-header__toolbar',
".vben-basic-table-header__toolbar"
).clientWidth;
};
@ -392,9 +359,14 @@
getSize: () => {
return unref(getBindValues).size as SizeType;
},
setToolBarWidth,
setToolBarWidth
};
function beforeSearchInfoChange(info){
setSearchFormData(info);
handleSearchInfoChange(info);
}
const { getHeaderProps } = useTableHeader(
getProps,
slots,
@ -404,16 +376,16 @@
getFormProps,
getBindValues,
tableAction,
handleSearchInfoChange,
beforeSearchInfoChange,
redoHeight,
getFormSlotKeys,
replaceFormSlotKey,
replaceFormSlotKey
);
createTableContext({ ...tableAction, wrapRef, getBindValues });
expose(tableAction);
emit('register', tableAction, formActions);
emit("register", tableAction, formActions);
return {
formRef,
@ -432,9 +404,9 @@
sum,
t,
tabelWidth,
calcToolBarWidth,
calcToolBarWidth
};
},
}
});
</script>
<style lang="less">
@ -600,6 +572,7 @@
// height: 100%;
// }
}
//.ant-table-tbody > tr.ant-table-row-selected td {
//background-color: fade(@primary-color, 8%) !important;
//}

View File

@ -1,5 +1,5 @@
import type { BasicTableProps, FetchParams, SorterResult } from '../types/table';
import type { PaginationProps } from '../types/pagination';
import type { BasicTableProps, FetchParams, SorterResult } from "../types/table";
import type { PaginationProps } from "../types/pagination";
import {
ref,
unref,
@ -9,13 +9,13 @@ import {
watch,
reactive,
Ref,
watchEffect,
} from 'vue';
import { useTimeoutFn } from '/@/hooks/core/useTimeout';
import { buildUUID } from '/@/utils/uuid';
import { isFunction, isBoolean } from '/@/utils/is';
import { get, cloneDeep, merge } from 'lodash-es';
import { FETCH_SETTING, ROW_KEY, PAGE_SIZE } from '../const';
watchEffect
} from "vue";
import { useTimeoutFn } from "/@/hooks/core/useTimeout";
import { buildUUID } from "/@/utils/uuid";
import { isFunction, isBoolean } from "/@/utils/is";
import { get, cloneDeep, merge } from "lodash-es";
import { FETCH_SETTING, ROW_KEY, PAGE_SIZE } from "../const";
interface ActionType {
getPaginationInfo: ComputedRef<boolean | PaginationProps>;
@ -30,6 +30,7 @@ interface SearchState {
sortInfo: Recordable;
filterInfo: Record<string, string[]>;
}
export function useDataSource(
propsRef: ComputedRef<BasicTableProps>,
{
@ -38,16 +39,17 @@ export function useDataSource(
setLoading,
getFieldsValue,
clearSelectedRowKeys,
tableData,
tableData
}: ActionType,
emit: EmitType,
emit: EmitType
) {
const searchState = reactive<SearchState>({
sortInfo: {},
filterInfo: {},
filterInfo: {}
});
const dataSourceRef = ref<Recordable[]>([]);
const rawDataSourceRef = ref<Recordable>({});
const searchFormData = ref({});
watchEffect(() => {
tableData.value = unref(dataSourceRef);
@ -60,15 +62,15 @@ export function useDataSource(
!api && dataSource && (dataSourceRef.value = dataSource);
},
{
immediate: true,
},
immediate: true
}
);
function handleTableChange(
isPaginateByDataSource = false,
pagination: PaginationProps,
filters: Partial<Recordable<string[]>>,
sorter: SorterResult,
sorter: SorterResult
) {
const { clearSelectOnPageChange, sortFn, filterFn } = unref(propsRef);
if (clearSelectOnPageChange) {
@ -151,7 +153,7 @@ export function useDataSource(
function updateTableDataRecord(
rowKey: string | number,
record: Recordable,
record: Recordable
): Recordable | undefined {
const row = findTableDataRecord(rowKey);
@ -171,7 +173,7 @@ export function useDataSource(
for (const key of rowKeys) {
let index: number | undefined = dataSourceRef.value.findIndex((row) => {
let targetKeyName: string;
if (typeof rowKeyName === 'function') {
if (typeof rowKeyName === "function") {
targetKeyName = rowKeyName(row);
} else {
targetKeyName = rowKeyName as string;
@ -183,18 +185,18 @@ export function useDataSource(
}
index = unref(propsRef).dataSource?.findIndex((row) => {
let targetKeyName: string;
if (typeof rowKeyName === 'function') {
if (typeof rowKeyName === "function") {
targetKeyName = rowKeyName(row);
} else {
targetKeyName = rowKeyName as string;
}
return row[targetKeyName] === key;
});
if (typeof index !== 'undefined' && index !== -1)
if (typeof index !== "undefined" && index !== -1)
unref(propsRef).dataSource?.splice(index, 1);
}
setPagination({
total: unref(propsRef).dataSource?.length,
total: unref(propsRef).dataSource?.length
});
}
@ -211,12 +213,12 @@ export function useDataSource(
const rowKeyName = unref(getRowKey);
if (!rowKeyName) return;
const { childrenColumnName = 'children' } = unref(propsRef);
const { childrenColumnName = "children" } = unref(propsRef);
const findRow = (array: any[]) => {
let ret;
array.some(function iter(r) {
if (typeof rowKeyName === 'function') {
if (typeof rowKeyName === "function") {
if ((rowKeyName(r) as string) === rowKey) {
ret = r;
return true;
@ -251,7 +253,7 @@ export function useDataSource(
beforeFetch,
afterFetch,
useSearchForm,
pagination,
pagination
} = unref(propsRef);
if (!api || !isFunction(api)) return;
try {
@ -259,7 +261,7 @@ export function useDataSource(
const { pageField, sizeField, listField, totalField } = Object.assign(
{},
FETCH_SETTING,
fetchSetting,
fetchSetting
);
let pageParams: Recordable = {};
@ -273,17 +275,16 @@ export function useDataSource(
}
const { sortInfo = {}, filterInfo } = searchState;
let params: Recordable = merge(
pageParams,
useSearchForm ? getFieldsValue() : {},
searchInfo,
opt?.searchInfo ?? {},
opt?.searchInfo || searchFormData.value || {},
defSort,
sortInfo,
filterInfo,
opt?.sortInfo ?? {},
opt?.filterInfo ?? {},
opt?.filterInfo ?? {}
);
if (beforeFetch && isFunction(beforeFetch)) {
params = (await beforeFetch(params)) || params;
@ -302,7 +303,7 @@ export function useDataSource(
const currentTotalPage = Math.ceil(resultTotal / pageSize);
if (current > currentTotalPage) {
setPagination({
current: currentTotalPage,
current: currentTotalPage
});
return await fetch(opt);
}
@ -313,23 +314,23 @@ export function useDataSource(
}
dataSourceRef.value = resultItems;
setPagination({
total: resultTotal || 0,
total: resultTotal || 0
});
if (opt && opt.page) {
setPagination({
current: opt.page || 1,
current: opt.page || 1
});
}
emit('fetch-success', {
emit("fetch-success", {
items: unref(resultItems),
total: resultTotal,
total: resultTotal
});
return resultItems;
} catch (error) {
emit('fetch-error', error);
emit("fetch-error", error);
dataSourceRef.value = [];
setPagination({
total: 0,
total: 0
});
} finally {
setLoading(false);
@ -352,6 +353,10 @@ export function useDataSource(
return await fetch(opt);
}
function setSearchFormData(data) {
searchFormData.value = data;
}
onMounted(() => {
useTimeoutFn(() => {
unref(propsRef).immediate && fetch();
@ -373,5 +378,6 @@ export function useDataSource(
insertTableDataRecord,
findTableDataRecord,
handleTableChange,
setSearchFormData
};
}