vue中keep-alive缓存多个页面

概述:vue开发项目时,需要缓存多个页面的情况

使用场景:例如:现有4个页面,页面1,页面2,页面3,页面4

要求:1、从1-2-3-4依次跳转时,每次都刷新页面,不进行缓存;

      2、从4-3-2-1依次返回时,页面不刷新,依次取缓存页面;

   总结:外到内都需要刷新,内到外皆获取缓存页面;

实现方式:keep-alive、vuex、路由钩子函数beforeRouteEnter、beforeRouteLeave

具体实现方式代码:

1、vuex部分:

复制代码
import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    keepAlive: []
  },
    mutations: {
        CHANGE_KEEPALIVE: (state, keepAlive) => {
            state.keepAlive = keepAlive
        }
    },
    // 这里getters可有可无
    getters: {
        keepAlive: state => state.keepAlive
    }
});

export default store;
复制代码

2、app.vue内部写法

复制代码
<template>
  <div id="app">
    <!-- 当使用了getters和computed进行监听时,可直接绑定keepAlive -->
    <keep-alive :include="keepAlive" >
    <!-- 也可不使用getters和computed进行监听,直接取值$store.state.keepAlive -->
    <!-- <keep-alive :include="$store.state.keepAlive" > -->
      <router-view></router-view>
    </keep-alive>
  </div>
</template>

<script>
export default {
  name: "app",
  data() {
    return {};
  },
  // 当使用了getters时可以选择添加computed进行监听
  computed: {
    keepAlive() {
      return this.$store.getters.keepAlive;
    },
  },
};
</script>
复制代码

3、页面1内部写法

复制代码
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.$store.commit('CHANGE_KEEPALIVE', ['页面1'])
    })
  },
// 跳转
    goLink(){
      this.$store.commit('CHANGE_KEEPALIVE', ['页面1','页面2','页面3']) 
      this.$router.push({
        path:'/页面2',
      })
    },   
复制代码

4、页面2内部写法

复制代码
beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.path.indexOf('页面3') > -1) {
          vm.$store.commit('CHANGE_KEEPALIVE', ['页面1','页面2'])
      }
    })
  },
  beforeRouteLeave (to, from, next) {
    if (to.path.indexOf('页面3') > -1) {
      this.$store.commit('CHANGE_KEEPALIVE', ['页面1','页面2', '页面3'])
    } else if (to.path.indexOf('页面1')>-1) {
      this.$store.commit('CHANGE_KEEPALIVE', ['页面1']) 
    }
    next()
  },
复制代码

5、页面3内部写法

复制代码
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (from.path.indexOf('页面4') > -1) {
          vm.$store.commit('CHANGE_KEEPALIVE', ['页面1','页面2', '页面3'])
      }
    })
  },
  beforeRouteLeave (to, from, next) {
    if (to.path.indexOf('页面4') > -1) {
      this.$store.commit('CHANGE_KEEPALIVE', ['页面1','页面2', '页面3'])
    } else if (to.path.indexOf('页面2') > -1) {
      this.$store.commit('CHANGE_KEEPALIVE', ['页面1','页面2']) 
    }
    next()
  },
复制代码

6、页面4不需要缓存则无需添加任何东西,正常书写即可,如需添加设置缓存,则按照上方更改添加配置即可

 

posted @   Alex-Song  阅读(1651)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示