0%

Vue3.x + Vite2.x 入门实战 06:Keep-alive 动态配置include实现页面缓存

概要内容

  • 实现步骤
    • 第一步:利用store状态管理缓存页面
    • 第二步:布局layout组件添加router-view相关配置
    • 第三步:在需要缓存的页面,添加路由守卫
  • 总结

实现步骤


  • 第一步:利用store状态管理缓存页面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    // src/store/modules/KeepAlive.ts
    //-------------------------------------------------------------------------
    const keepAliveModule = {
    namespaced: true,
    state: {
    caches: [],
    },
    mutations: {
    ADD(state, name) {
    if (state.caches.indexOf(name) < 0) {
    state.caches.push(name)
    }
    },
    REMOVE(state, name) {
    state.caches = state.caches.filter(item => item != name);
    },
    CLEAN(state) {
    state.caches = [];
    }
    }
    }
    //-------------------------------------------------------------------------
    export default keepAliveModule;
    //-------------------------------------------------------------------------
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // src/store/index.ts
    import { createStore } from 'vuex'
    import keepAliveModule from './modules/KeepAlive';
    //-------------------------------------------------------------------------
    const store = createStore({
    modules: {
    keepAlive: keepAliveModule
    },
    getters: {
    keepAlive: (state) => (state as any).keepAlive,
    }
    });
    //-------------------------------------------------------------------------
    export default store;
    //-------------------------------------------------------------------------
  • 第二步:布局layout组件添加router-view相关配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <template>
    <div class="MainWrapper">
    <router-view v-slot="{ Component }">
    <transition>
    <keep-alive :include="$store.state.keepAlive.caches">
    <component :is="Component" />
    </keep-alive>
    </transition>
    </router-view>
    </div>
    </template>
  • 第三步:在需要缓存的页面,添加路由守卫

    • beforeRouteEnter:添加缓存页面
    • beforeRouteLeave:删除缓存页面
    • 提示:控制逻辑放置一块,方便管理

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      //src/views/variety.vue
      export default defineComponent({
      name: "variety",
      components: {
      },
      setup(props, context) {
      },
      beforeRouteEnter(to, from, next) {
      if (to.path == "/product/variety") {
      store.commit("keepAlive/ADD", to.name);
      }
      next();
      },
      beforeRouteLeave(to, from, next) {
      if (to.name != "pic-editor") {
      store.commit("keepAlive/REMOVE", from.name);
      }
      next();
      },
      });

总结

  • 特别提醒:keep-alive :include 使用的是页面组件name,所以一定要记得给页面组件命名

参考文献


以上:如发现有问题,欢迎留言指出,我及时更正

如何文章对你有益,请给我买杯豆浆喝