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 @ 2021-09-27 11:41  Alex-Song  阅读(1477)  评论(0编辑  收藏  举报