🔥 Vue 进阶:KeepAlive 动态缓存,如何让页面按需“冬眠”?

90 阅读2分钟

前言

Vue 开发中,页面缓存是一个让人又爱又恨的功能。爱它,是因为它可以大大提升用户体验;恨它,是因为默认的缓存方式太“死板”了!今天,我们就来聊聊如何让 Vue 的 KeepAlive 缓存变得“灵动”起来,按需缓存页面,就像给页面开启了一个“冬眠模式”✨

场景引入:页面缓存的“尴尬瞬间”

假设你正在开发一个单页面应用,有三个页面:A、B 和 C。用户从 A 跳转到 B,然后从 B 跳转到 C,最后从 C 返回 B。你希望:

  • 当从 B 跳转到 C 时,B 页面被缓存,C 返回 B 时页面内容保持不变(用户体验满分)。
  • 当从 B 返回 A 时,B 页面不被缓存,再次从 A 进入 B 时页面重新初始化(避免数据混乱)。

但是,Vue 默认的 KeepAlive 是静态的,无法满足这种复杂的动态需求。怎么办呢?🤔

解决方案:动态控制 KeepAlive 缓存

别担心,我们可以通过 Vue Router 和 Pinia 来实现动态缓存!下面就是关键代码和实现思路。

1. APP.vue:KeepAlive 的“指挥官”

APP.vue 中,我们用 KeepAlive 包裹路由组件,并通过 Pinia 的 cachedViews 动态控制缓存页面。

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="cachedViews">
      <component
        :is="Component"
        v-if="$route.meta.keepAlive"
        :key="$route.meta.name"
      />
    </keep-alive>
  </router-view>
</template>

<script setup>
import { storeToRefs } from 'pinia';
import { useCacheStore } from './stores/keepAliveCache.js';

const cacheStore = useCacheStore();
const { cachedViews } = storeToRefs(cacheStore);
</script>

2. keepAliveCache.js:缓存页面的“管理员”

我们用 Pinia 创建一个 keepAliveCache store,管理缓存页面的名称列表。

import { defineStore } from 'pinia';

export const useCacheStore = defineStore('cache', {
  state: () => ({
    cachedViews: ['...'], // 固定缓存的页面,无需动态处理的页面初始化添加
  }),
  actions: {
    addCache(name) {
      if (!this.cachedViews.includes(name)) {
        this.cachedViews.push(name);
      }
    },
    removeCache(name) {
      this.cachedViews = this.cachedViews.filter(view => view !== name);
    },
    clearCache() {
      this.cachedViews = [];
    },
  },
});

3. B 页面:动态缓存的“主角”

在 B 页面中,通过 onBeforeRouteLeave 钩子动态控制缓存逻辑。通过在路由守卫中控制需要缓存的目标路由实现动态控制

<script setup>
import { useCacheStore } from '../../../stores/keepAliveCache.js';
import { onBeforeRouteLeave } from 'vue-router';

const cacheStore = useCacheStore();

// 初始开始 KeepAlive 缓存
cacheStore.addCache('CarDiyPayDeposit');

// 动态控制当前页面是否缓存
onBeforeRouteLeave((to, from, next) => {
  const cachePath = ['/C']; // C 页面的路径
  if (!cachePath.includes(to.path)) {
    // 如果跳转到非缓存路径,移除 B 页面缓存
    cacheStore.removeCache('B');
  }
  next();
});
</script>

互动环节:你遇到过哪些缓存“坑”?

评论区见!如果你在开发中遇到过类似的缓存问题,或者有更好的解决方案,欢迎在评论区分享你的经验。让我们一起“填坑”!👇

总结

通过 Vue Router 和 Pinia,我们可以轻松实现 KeepAlive 的动态缓存控制。这种方案不仅灵活,还能根据实际需求进行扩展和优化。希望本文能帮你解决开发中的“小烦恼”,让你的页面缓存变得“灵动”起来!

如果你觉得这篇文章对你有帮助,别忘了点赞和关注哦!我们下次见!✨