保留上一次查询记录
需求:后台页面,点击列表操作的详情按钮进入详情页面后返回需保留上一次的查询记录。
思路:
- pinia创建store用于查询数据的保存和获取
- 编写hooks抽离页面重复逻辑
- Vue页面使用
pinia创建store用于查询数据的保存和获取
import { defineStore } from 'pinia';
/**
* 主要用于页面切换返回上一级时的搜索状态保留
*/
export const useStoreSearch = defineStore('searchStore', {
state: () => ({
searchRecord: {},
}),
actions: {
setSearchRecord(searchRecord) {
this.searchRecord = searchRecord;
},
},
getters: {
getSearchRecord() {
return this.searchRecord;
},
},
});
编写hooks抽离页面重复逻辑
import { useStoreSearch } from '@/stores/keepSearch';
import { onBeforeRouteLeave } from 'vue-router';
let isMatchName = false;
/**
* @param { Object } searchForm 当前的搜索表单对象
* @param { Array } pathName 具备保存表单查询功能的路由名称数组
* @returns { Function } assignSearchValues - 合并搜素字段
* @returns { Function } saveSearchQuery - 保存查询条件至searchStore
*/
export default function useKeepParams(searchForm, pathName) {
const searchStore = useStoreSearch();
function saveSearchQuery() {
searchStore.setSearchRecord(searchForm);
}
// 通过onBeforeRouteLeave路由API判断前往的路由是否匹配为合并方法提供判断条件
onBeforeRouteLeave((to) => {
const targetName = to.name;
if (pathName.includes(targetName)) {
isMatchName = true;
}
});
function assignSearchValues() {
const searchRecord = searchStore.getSearchRecord;
if (isMatchName && Object.keys(searchRecord).length) {
Object.assign(searchForm, searchRecord);
isMatchName = false;
}
}
return {
assignSearchValues,
saveSearchQuery,
};
}
页面调用
// 先引入hooks
import useKeepParams from '@/hooks/keepParams';
// 保留上一次搜索记录
const { assignSearchValues, saveSearchQuery } = useKeepParams(searchForm, ['RaceDetail']);
// 获取数据时调用saveSearchQuery保存当前搜索条件
async function getTableData() {
try {
saveSearchQuery();
isLoading.value = true;
const formContent = {
reportingTime: searchForm.createTime?.[0],
reportingEndTime: searchForm.createTime?.[1],
...searchForm,
};
const tableList = await getRaceList(formContent);
} catch (error) {
console.log(error);
} finally {
isLoading.value = false;
}
}
// 挂载时将存储的搜索条件合并、assignSearchValues方法内部有做判断
onMounted(() => {
assignSearchValues();
getTableData();
});