解决vue 部分页面缓存,部分页面不缓存的问题

前端时间项目迭代,其中有个需求 在vue里面,有a.b.c三个页面,要达到的效果是从a页面进去b页面,b页面需要刷新,但若从b页面进入c页面了以后再回到b页面,b页面需要保留之前的值,不做刷新;

第一想到的是:<router-view v-if="$route.meta.keepAlive"></router-view> ;但是由于v-if 每次会销毁页面元素,导致第一次是缓存不成功的;在网上也找到过window.reload();这种方法,但是页面会有一瞬间的空白,用户体验不是很好; 最后找了一种方法,vuex结合路由守卫可以达到此效果,具体代码如下:

首先app.vue

javascript 复制代码
//js
 
computed: {
            keepAlive () {
                return this.$store.getters.keepAlive
            }
        },
 
//html
<keep-alive  :include='keepAlive'>
    <router-view></router-view>
</keep-alive>
vuex 中需要定义keepAlive


import Vue from 'vue'
import Vuex from 'vuex'
 
 
Vue.use(Vuex)
 
var store = new Vuex.Store({
    // 定义状态
    state: {
         
        keekAlives:[],
         
    },
    mutations:{  //更改 Vuex 的 store 中的状态
        SET_KEEP_ALIVE:function(state, keekAlives){
           return state.keekAlives = keekAlives;
        }
    },
    getters: {
      keepAlive: function(state){
          return state.keekAlives
    //   keepAlive: state => state.keekAlives
      }
    }
})
 
export default store
最后在需要缓存的页面进行判断

beforeRouteEnter (to, from, next) {
     next(vm => {
               if (from.name=="serve") {
                    vm.$store.commit('SET_KEEP_ALIVE', ['addProject'])
               }
            })
        },
        beforeRouteLeave (to, from, next) {
            if (to.name == "companySearch") {
               this.$store.commit('SET_KEEP_ALIVE', ['addProject'])
            } else if (to.name=="serve" || to.name=="addSuccess") {
         this.$store.commit('SET_KEEP_ALIVE', []) 
            }
            next()
        },

这样就实现了vue 部分页面缓存,部分页面不缓存的问题!

相关推荐
丷丩1 天前
MapLibre GL JS第47课:添加动画图标
javascript·gis·动画·mapbox·maplibre
独泪了无痕1 天前
Vue3中防御XSS攻击的“特效药”-DOMPurify
前端·vue.js·安全
宸丶一1 天前
Day 10:LangGraph - Agent 的图执行引擎
java·windows·python
hikktn1 天前
Excel 导出 OOM 预防实战:30 万行从堆溢出到 50MB 的演进
java·excel·easyexcel
快乐的哈士奇1 天前
【Next.js实战①】Gmail API 按柜号检索邮件:OAuth 双 Cookie 与搜索 Fallback
开发语言·javascript·ecmascript
风味蘑菇干1 天前
WTomcat服务器
java·服务器
无关86881 天前
Redis Bitmaps 用户签到系统设计方案
数据库·redis·缓存
云水一下1 天前
Vue.js从零到精通系列(五):全局状态管理——Pinia 核心与实践
前端·javascript·vue.js
燕-孑1 天前
tomcat详解(基础到高级生产)
java·tomcat
码不停蹄的玄黓1 天前
Spring Bean 生命周期
java·后端·spring