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

相关推荐
云烟成雨TD1 天前
Spring AI Alibaba 1.x 系列【6】ReactAgent 同步执行 & 流式执行
java·人工智能·spring
于慨1 天前
Lambda 表达式、方法引用(Method Reference)语法
java·前端·servlet
swg3213211 天前
Spring Boot 3.X Oauth2 认证服务与资源服务
java·spring boot·后端
像我这样帅的人丶你还1 天前
别再让JS耽误你进步了。
css·vue.js
gelald1 天前
SpringBoot - 自动配置原理
java·spring boot·后端
@yanyu6661 天前
07-引入element布局及spring boot完善后端
javascript·vue.js·spring boot
殷紫川1 天前
深入理解 AQS:从架构到实现,解锁 Java 并发编程的核心密钥
java
一轮弯弯的明月1 天前
贝尔数求集合划分方案总数
java·笔记·蓝桥杯·学习心得
chenjingming6661 天前
jmeter线程组设置以及串行和并行设置
java·开发语言·jmeter
殷紫川1 天前
深入拆解 Java volatile:从内存屏障到无锁编程的实战指南
java