import type { Ref } from 'vue';
|
import { onActivated, onDeactivated, onMounted, onUnmounted, ref, watch } from 'vue';
|
import { deepClone } from '/@/utils/other';
|
import { convertListToTree, flatten } from '/@/utils/util';
|
|
/**
|
*
|
* @param tableData 原始数据,接口拿到的数据
|
* @param queryParams 查询参数 form
|
* @param getTableData
|
* @param isTree 是否是 ParentID 构建树的数组
|
* @param isChildTree 是否是 Children 构建的树的数组
|
* @returns
|
*/
|
export const useQueryTable = (
|
tableData: Ref<any[]>,
|
queryParams: Ref<Object>,
|
getTableData: () => void | Promise<void>,
|
isTree?: Boolean,
|
isChildTree = false
|
) => {
|
const displayTableData = ref(null as any[]);
|
|
const resetQuery = () => {
|
for (const key in queryParams.value) {
|
if (typeof queryParams.value[key] === 'string') {
|
queryParams.value[key] = '';
|
} else if (typeof queryParams.value[key] === 'number') {
|
queryParams.value[key] = null;
|
}
|
}
|
getTableData();
|
};
|
|
const handleQueryTable = () => {
|
if (checkQueryParamsIsEmpty()) {
|
return getTableData();
|
}
|
const convertData = isChildTree ? flatten(tableData.value) : tableData.value;
|
const filterTableData = convertData.filter((item: any) => {
|
return Object.keys(queryParams.value).every((key) => {
|
const queryValue = queryParams.value[key];
|
let queryStr = '';
|
if (queryValue !== null) {
|
queryStr = String(queryValue);
|
}
|
|
return String(item[key]).toLowerCase().includes(queryStr.trim().toLowerCase());
|
});
|
});
|
displayTableData.value = filterTableData;
|
};
|
const handleTableDataChange = isTree
|
? (val) => {
|
// convertListToTree 克隆原始数据,不影响原始数据
|
displayTableData.value = convertListToTree(deepClone(val));
|
}
|
: (val) => {
|
displayTableData.value = val;
|
};
|
|
const checkQueryParamsIsEmpty = () => {
|
return Object.values(queryParams.value).every((objectValue) => objectValue === '' || objectValue === null);
|
};
|
|
watch(
|
() => tableData.value,
|
(val) => {
|
handleTableDataChange(val);
|
},
|
{ immediate: true }
|
);
|
|
return {
|
checkQueryParamsIsEmpty,
|
resetQuery,
|
handleQueryTable,
|
displayTableData,
|
};
|
};
|