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

相关推荐
q***07141 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
q***49861 小时前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
Hammer Ray3 小时前
SourceMap知识点
javascript·sourcemap
沐浴露z4 小时前
【微服务】基本概念介绍
java·微服务
Z3r4y4 小时前
【代码审计】RuoYi-4.7.3&4.7.8 定时任务RCE 漏洞分析
java·web安全·ruoyi·代码审计
Kuo-Teng6 小时前
LeetCode 160: Intersection of Two Linked Lists
java·算法·leetcode·职场和发展
Jooou6 小时前
Spring事务实现原理深度解析:从源码到架构全面剖析
java·spring·架构·事务
盖世英雄酱581366 小时前
commit 成功为什么数据只更新了部分?
java·数据库·后端
CDwenhuohuo7 小时前
微信小程序里用 setData() 修改数据并打印输出 的几种写法
javascript·微信小程序·小程序