73 lines
2.2 KiB
JavaScript
73 lines
2.2 KiB
JavaScript
import { tools } from "@cqsjjb/jjb-common-lib";
|
|
import useGetUrlQuery from "../useGetUrlQuery";
|
|
|
|
const { query } = tools.router;
|
|
|
|
/**
|
|
* 处理搜索条件缓存到 URL
|
|
*/
|
|
export default function useUrlQueryCriteria() {
|
|
/**
|
|
* 将搜索表单项和分页参数缓存到 URL 中
|
|
*/
|
|
function setUrlCriteriaQuery(searchForm, pagination) {
|
|
// 将对象转换为键值对字符串格式
|
|
const getJoinString = (data) => {
|
|
const keys = [];
|
|
const values = [];
|
|
Object.entries(data).forEach(([key, value]) => {
|
|
if (value) {
|
|
keys.push(key);
|
|
if (Array.isArray(value)) {
|
|
// 数组值使用方括号包裹,并用竖线分隔
|
|
values.push(`[${value.join("|")}]`);
|
|
}
|
|
else {
|
|
values.push(value);
|
|
}
|
|
}
|
|
});
|
|
return { keys: keys.join(","), values: values.join(",") };
|
|
};
|
|
|
|
// 获取搜索表单和分页数据的键值对字符串
|
|
const searchFormData = getJoinString(searchForm);
|
|
const paginationData = getJoinString(pagination);
|
|
|
|
// 将数据存储到 URL 查询参数中
|
|
query.searchFormKeys = searchFormData.keys;
|
|
query.searchFormValues = searchFormData.values;
|
|
query.paginationKeys = paginationData.keys;
|
|
query.paginationValues = paginationData.values;
|
|
}
|
|
|
|
/**
|
|
* 从 URL 中获取缓存的查询参数
|
|
*/
|
|
function getUrlCriteriaQuery(keysStr, valuesStr) {
|
|
const query = useGetUrlQuery();
|
|
// 将键值字符串分割为数组
|
|
const keys = query[keysStr] ? query[keysStr].split(",") : [];
|
|
const values = query[valuesStr] ? query[valuesStr].split(",") : [];
|
|
|
|
// 构建结果对象
|
|
const resultMap = {};
|
|
keys.forEach((key, index) => {
|
|
if (values[index]) {
|
|
// 处理数组值(方括号包裹的值)
|
|
if (values[index].startsWith("[") && values[index].endsWith("]")) {
|
|
const arrayContent = values[index].substring(1, values[index].length - 1);
|
|
resultMap[key] = arrayContent ? arrayContent.split("|") : [];
|
|
}
|
|
else {
|
|
// 处理普通值
|
|
resultMap[key] = values[index];
|
|
}
|
|
}
|
|
});
|
|
return resultMap;
|
|
}
|
|
|
|
return { setUrlCriteriaQuery, getUrlCriteriaQuery };
|
|
}
|