解决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 部分页面缓存,部分页面不缓存的问题!

相关推荐
Java后端的Ai之路16 小时前
01、Python - 设计模式介绍
java·人工智能·python·设计模式·通用
zzzll111116 小时前
大模型技术原理与应用实践
java·数据库·人工智能
asdfg125896316 小时前
java.util包中的ArrayList&&Collections的目的和用途
java·arraylist·collections
余额瞒着我当琳16 小时前
C++STL--list底层实现,迭代器分类,模拟list的迭代器封装、实现
java·开发语言·c++
吴声子夜歌17 小时前
Java面试——数据结构(二)
java·数据结构·面试
kyle~17 小时前
计算机系统 --- 缓存一致性
开发语言·c++·缓存·计算机系统
栀栀栀栀栀栀17 小时前
2026/8/23 maven springboot
java·spring boot·maven
SeaDhdhdhdhdh1 天前
MCP Server 搭建与使用指南
java·ai·agent·mcp
YH55269841 天前
GPT‑5.6 Sol 原本支持 1M 上下文,Codex 现已放开此前限制,如何看待这次调整?
java·jvm·人工智能·gpt·算法·chatgpt
AI_小站1 天前
刚面完百度的 Agent 开发岗,我才发现:世界就是个巨大的草台班子
java·开发语言·人工智能·spring·百度·langchain