当前位置: 首页 > Web前端 > vue.js

vue缓存页面解决方案

时间:2023-04-01 00:38:04 vue.js

背景在日常业务开发中,遇到了一个问题。从列表页进入子页,再次返回列表页时,用户希望保留之前的搜索信息,比如选择Pagination是第4页或者输入的搜索条件(id)等。列表页->子页子页->列表页(此时保留最后一条信息)思路是利用持久化数据状态来保留之前的记录信息。这是我第一个想到的方法,用vuex,cookie,locaStorage,indexdb,用的什么存储方式,目的只是为了保存我们之前的操作记录,比如我输入的搜索信息,还有的分页信息我点击的列表。流程如下1??首先定义一个配置项,配置项如下:constRouterCached=newMap([['ListName',['OneChildName','TwoChildName']]]);2??在List组件的beforeRouteLeave钩子中缓存数据3??在List组件的beforeRouteEnter钩子中读取缓存数据,并执行恢复操作。这里有一个前提,fromhook必须是RouterCached对应的路由名,即如果不在配置表中,我们就清空缓存,不做任何恢复操作。使用vue中的keep-alive组件引入keep-alive。key-alive添加了几个重要的属性。借助社区中的解决方案,得到以下思路。include属性与router-view配合使用。这里的目的是让缓存视图中的组件保持活动状态。CachedViews是这里组件的名称集合。2.封装cacheView操作接下来,我们包装store中cacheView的几个操作,添加需要缓存的组件,清除指定缓存的组件,清除所有缓存的组件cachedcomponentsimport{Route}from'vue-router';导出接口RouteView扩展部分{title?:string}conststate={cachedViews:[]};constmutations={ADD_CACHED_VIEW:(status,route:RouteView)=>{if(status.cachedViews.includes(route.name))返回;如果(route.meta&&route.meta.cache){status.cachedViews.push(route.name);}},DEL_ALL_CACHED_VIEWS:(状态)=>{status.cachedViews=[];},DEL_CACHED_VIEW:(status,route:RouteView)=>{constindex=status.cachedViews.indexOf(route.name);if(index>-1){status.cachedViews.splice(index,1);}},};constactions={addCachedView({commit},route:RouteView){commit('ADD_CACHED_VIEW',route);},delAllCachedViews({commit}){commit('DEL_ALL_CACHED_VIEWS');},delCachedView({commit},route:RouteView){commit('DEL_CACHED_VIEW',route);},};exportdefault{state,mutations,actions};3.全局锁子摘绳保存在全局的路由锁子router在.beforeEach中添加该方法的逻辑consthandlerCached=(to:RouteView,from:RouteView)=>{const{cachedViews}=store.state;//清空除列表到详情的缓存,列表和详情需要互相回传nameif(!(to.meta.isback&&to.meta.isback.includes(from.name))){store.dispatch('appMain/delAllCachedViews');}//回去的时候,一个一个清空缓存链cachedViews.forEach((name:string,index:number)=>{if(name===from.name&&cachedViews[index-1]&&cachedViews[index-1]===to.name){store.dispatch('appMain/delCachedView',from);}});常量{名称}=到;if(name){store.dispatch('appMain/addCachedView',to);}};4。路由配置的最后一步是在配置中的meta字段中,添加isback和cache字段。这两个领域的思路和方法是一样的cache表示需要缓存的组件(List),isback表示从该组件返回需要缓存的组件(Child)。以下配置:[{path:'list',component:LayoutEmpty,meta:{title:'DeviceControl',hiddenPage:true,},redirect:'/device/list/deviceLists',children:[{path:'deviceLists',代码:'deviceLists',名称:'DeviceLists',组件:DeviceLists,元:{标题:'ListName',缓存:true,},隐藏:true,},{路径:'detail',代码:'deviceDetail',名称:'DeviceDetial',组件:DeviceDetail,隐藏:true,meta:{title:'OneChildName',onHidden:true,isback:'DeviceLists'},},{路径:'log',代码:'log',名称:'Log',组件:Log,隐藏:true,meta:{title:'TwoChildName',onHidden:true,isback:'DeviceLists'},},]],},]??Notes最后需要注意的是isback对应的名字是需要缓存的名字。是routerConfig中的name,组件中的name也需要保持一致