vue-router keepalive 页面缓存的实现(详情返回列表并记录列表页状态)
实现场景:
当前页面有不同的状态切换,并且有相应的列表值。比如:淘宝的订单列表页面的布局方式。有已发货,待发货,已收货,全部订单等。当点击已发货下的订单列表时,可以跳转到订单详情页面。当点击返回的时候,返回到已发货/待发货状态下相应的列表位置。并且页面不会发送请求。
实现原理:
kee-alive
是 Vue
内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染
实现方式:
1,APP.vue
<template> <div id="app" class="mescroll-touch" v-cloak> <keep-alive :include="include"> <!-- v-if="!$route.meta.keepAlive" --> <router-view></router-view> </keep-alive> <!-- <router-view v-if="!$route.meta.keepAlive"></router-view> --> </div> </template>
在data里定义一个字段 include:[],并且在watch里监听$route
watch: { $route(to, from) { // 如果要to(进入)的页面是需要keepAlive缓存的,把name push进include数组中 if (from.meta&&to.meta&&from.meta.deepth&&to.meta.keepAlive) { !this.include.includes(to.name) && this.include.push(to.name); } // 如果 要 form(离开) 的页面是 keepAlive缓存的, // 再根据 deepth 来判断是前进还是后退 // 如果是后退: if (from.meta&&to.meta&&from.meta.keepAlive && to.meta.deepth < from.meta.deepth) { const index = this.include.indexOf(from.name); index !== -1 && this.include.splice(index, 1); } // 如果回到了首页,那么缓存为空 if(to.meta.deepth==1){ this.include=[] } } },
2,配置路由属性,在router里的index.js 里定义属性meta: { title: 'xxx',keepAlive:true,deepth:5},这里注意name 值要跟页面组件里的name值保持一致,否则无效。关于
deepth的值 首页 < 列表 < 详情 这样可以做到前进后退 区分要缓存哪一页。
{ name:'couponIndex', path:'/couponIndex', component: routerData.router.coupon_index, meta: { title: '卡券',deepth:4} }, { name:'couponInfo', path:'/couponInfo', component: routerData.router.coupon_info, meta: { title: '卡券详情',keepAlive:true,deepth:6} }, { name:'couponList', path:'/couponList', component: routerData.router.coupon_list, meta: { title: '我的卡包',keepAlive:true,deepth:5} },
3,在 couponList.vue 里 定义name: "couponList;couponInfo.vue 里定义 name: "couponInfo"。在meta里定义keeplive:true 的页面里分别定义name值即可。
4,如果要缓存的页面里存在滚动事件监听,比如上拉加载更多的时候,滚动监听方法的触发和移除 放在activated和deactivated两个生命周期中。
activated(){ window.addEventListener('scroll', this.initHeight); }, //离开删除绑定事件 deactivated() { window.removeEventListener("scroll",this.initHeight); },
否则会出现滚动加载乱触发的情况。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本