Vue2 编辑返回保留分页页码解决方案
2026/6/23 2:33:57
网站开发
Vue2 编辑返回保留分页页码解决方案问题根源this.$router.back()只是单纯回退历史记录列表页分页、搜索筛选、页码是存在组件 data 里的路由回退后组件会重新加载丢失之前分页状态。四种主流方案按推荐程度排序方案1路由传参最简单无需缓存1. 列表页跳转编辑时带上当前分页参数// 列表页 点击编辑handleEdit(row){constpagethis.pageNum;// 当前页码constsizethis.pageSize;// 每页条数this.$router.push({path:/product/edit/${row.id},query:{page,size}// 把分页存在query})}2. 编辑页保存时携带页码返回列表// 编辑确认按钮asyncsubmit(){awaitapi.save(this.form);// 获取跳转过来时携带的分页参数const{page,size}this.$route.query;if(page){// 跳回列表并带上分页自动加载对应页this.$router.push({path:/product/list,query:{page,size}})}else{this.$router.back();}}3. 列表页 created 读取 query 恢复分页created(){// 路由带分页则赋值if(this.$route.query.page){this.pageNumNumber(this.$route.query.page);this.pageSizeNumber(this.$route.query.size);}this.getList();// 重新请求对应页码数据}优点简单无副作用缺点url会拼接分页参数方案2keep-alive 缓存列表组件最优体验页面不会重新请求直接保留上次滚动、分页、筛选状态1. 路由配置开启缓存!-- App.vue / 路由出口 -- router-view v-if$route.meta.keepAlive keep-alive/router-view router-view v-else/router-view2. router/index.js 给列表路由加标记{path:/product/list,name:ProductList,component:ProductList,meta:{keepAlive:true}// 标记需要缓存},{path:/product/edit/:id,component:ProductEdit}3. 编辑完成直接回退即可submit(){awaitsaveApi();this.$router.back();// 列表组件被缓存页码数据全部保留}补充如果需要编辑完强制刷新列表监听activated钩子判断是否从编辑页返回// ProductList.vueactivated(){// 判断上一页是编辑页刷新数据if(this.$route.meta.fromEdit){this.getList();this.$route.meta.fromEditfalse;}}跳转编辑时打标记handleEdit(){this.$route.meta.fromEdittrue;this.$router.push(/product/edit/${id})}方案3Vuex / Pinia 存储分页状态多页面共用适合多处进入编辑、需要全局保存分页store 定义分页变量state:{productPage:{pageNum:1,pageSize:10}},mutations:{setProductPage(state,payload){state.productPagepayload}}列表每次请求前更新storethis.$store.commit(setProductPage,{pageNum:this.pageNum,pageSize:this.pageSize})列表 created 读取store恢复created(){constpagethis.$store.state.productPage;this.pageNumpage.pageNum;this.pageSizepage.pageSize;this.getList();}方案4本地存储 localStorage刷新页面也不丢失// 列表切换页码时保存changePage(){localStorage.setItem(productPage,JSON.stringify({pageNum:this.pageNum,pageSize:this.pageSize}))this.getList()}// 列表初始化读取created(){constcachelocalStorage.getItem(productPage);if(cache){const{pageNum,pageSize}JSON.parse(cache);this.pageNumpageNum;this.pageSizepageSize;}this.getList();}推荐组合使用方案项目通用列表路由加keepAlive缓存返回直接保留分页体验最好如需编辑后刷新列表搭配路由meta标记在activated重新请求接口若页面复杂、多入口跳转补充路由query兜底踩坑提醒this.$router.back()无法携带参数单纯回退一定会丢失组件内数据不要只用backkeep-alive 缓存后created不会再次执行改用activated处理刷新逻辑分页参数一定要转数字query获取的是字符串请求接口会报错