<!-- 搜索按钮组件
使用方法:1.组件已经全局暴露,可以直接使用
<search-button
ref="searchButton" //组件ref名称父组件调用saveFilterParams保存函数会使用到
:table-name="$route.name" //表格名称-作为唯一标识使用,如果是表格主页面那么$route.name是不错的选择
:params="queryParams" // 查询参数,要保存到vuex的参数
@search="handleQuery" // 子组件搜索按钮触发事件,会返回保存的查询参数||默认查询参数
/>
<search-button
ref="searchButton"
:table-name="$route.name"
:params="queryParams"
@search="handleQuery"
/>
2.handleQuery方法接收查询参数,并调用获取表格数据方法
3.表格数据获取方法内 调用本组件saveFilterParams方法保存查询参数
this.$refs.searchButton.saveFilterParams()
4.查询接口then中加入判断 防止有数据但分页数过大导致返回为空
if (this.tableList.length === 0 && this.total > 0) {
this.currentPage = 1
this.getList()
}
// 为了分页器展示页码与实际页码一致
this.currentPage = this.queryParams.pageQuery.pageNum
5.为了保证分页器分页正常显示,加入currentPage,和查询参数内pageNum参数一致
分页器page为currentPage
currentPage(newValue) {
// 分页参数变化时,同步改变查询参数里的分页参数用以下次重载使用
this.queryParams.pageQuery.pageNum = newValue
}
-->
<template>
<div>
<el-button
type="primary"
icon="el-icon-search"
size="mini"
@click="onSearch"
>搜索</el-button
>
<el-button icon="el-icon-refresh" size="mini" @click="onReset"
>重置</el-button
>
</div>
</template>
<script>
export default {
props: {
// 表格名称,用于唯一标识不同的表格
tableName: {
type: String,
default: "",
},
// 默认的搜索参数
params: {
type: Object,
default: () => ({}),
},
},
data() {
return {
// 存储查询参数,用于后续的搜索操作
filterParams: {},
};
},
mounted() {
// 加载查询参数,从store中获取或使用默认值
this.loadFilterParams();
},
methods: {
// 加载查询参数
loadFilterParams() {
// 从Vuex store中获取查询参数,如果没有找到,则使用默认参数
this.filterParams =
this.$store.getters.filterParams.get(this.tableName) || this.params;
// 向父组件发送查询参数
this.$emit("search", this.filterParams);
},
// 搜索事件处理
onSearch() {
// 触发搜索事件,将当前的查询参数传递给监听器
this.$emit("search", this.filterParams);
},
// 重置按钮的点击事件处理
onReset() {
// 遍历查询参数,将非分页相关的参数重置为null
for (const key in this.filterParams) {
if (key.includes("page")) {
this.filterParams[key].pageNum = 1;
} else {
this.filterParams[key] = null;
}
}
// 触发搜索事件
this.onSearch();
},
// 保存查询参数到store中(由父组件获取表格数据时调用)
saveFilterParams() {
// 将查询参数保存到store中
this.$store.dispatch("tableFilterParams/setTableFilterParams", {
tableName: this.tableName,
params: this.filterParams,
});
},
},
};
</script>
搜索后将搜索参数保存至vuex实践
最新推荐文章于 2024-09-26 01:42:12 发布