Vue3中KeepAlive的使用

  我们在开发一个功能是,经常会遇到从一个列表页面,点击列表项跳转到详情页面的需求,理想的情况下,从详情页面返回到列表页,应该回到跳转前的状态,可以继续浏览其他内容;但是在没做任何处理的情况下,返回列表页后,列表页会被刷新,回到初始的状态,这就与我们的预设不符;为了实现这样的需求,我们需要使用keep-alive组件来缓存列表页面的状态,让其不被刷新,这样就可以愉快的继续浏览啦。

  下面就是我们使用keep-alive组件的一些步骤:(ps:项目使用vue3、vue-router、pinia、typescript)

1、声明路由的Meta扩展数据类型,用来在路由中配置哪些页面需要被缓存

router.d.ts

import "vue-router";

declare module "vue-router" {

  interface RouteMeta extends MyRoute.RouteMeta {
    title: string;
    keepAlive?: boolean; // 该路由页面是否需要缓存
    keepAlivePages?: Array<string>;  // 配置需要缓存的跳回来源(从某页面回到该页面,该页面缓存,其他页面回到该页面,该页面不缓存)
    canBack?: boolean; // 是否可以返回
  }

}

 

2、配置路由信息,以文章列表和详情页面为例

分模块配置路由文件library.ts

import { RouteComponent, RouteRecordRaw } from "vue-router";

const routes: Array<RouteRecordRaw> = [
 {
    path: "library/list",
    name: "libraryList",
    meta: { title: "文章列表", keepAlive: true, keepAlivePages: ["libraryDetail"] },
    component: (): RouteComponent => {
      return import(/* webpackChunkName: "pages_knowledge_library" */ "@/views/pages/knowledge/library/index.vue");
    }
  },
  {
    path: "library/detail",
    name: "libraryDetail",
    meta: { title: "文章详情", canBack: true },
    component: (): RouteComponent => {
      return import(/* webpackChunkName: "pages_knowledge_library_detail" */ "@/views/pages/knowledge/library/detail.vue");
    }
  }
];

export default routes;

 

3、声明页面组件的名称,与配置的名称一致:keep-alive 组件会根据组件的 name 选项进行匹配,所以组件如果想要条件性地被 keep-alive 缓存,就必须显式声明一个 name 选项。

在 3.2.34 或以上的版本中,使用 <script setup> 的单文件组件会自动根据文件名生成对应的 name 选项,即使是在配合 <KeepAlive> 使用时也无需再手动声明。

但在项目中我们是分模版开发,业务组件文件重名的几率还是挺大的,所以我们还是需要显式声明组件的name属性。

library/index.vue

<template>
<!-- 页面模版 -->
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({ name: "libraryList" });
</script>

<script lang="ts" setup>
// 页面绑定数据
<script>

library/detail.vue

<template>
<!-- 页面模版 -->
</template>

<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({ name: "libraryDetail" });
</script>

<script lang="ts" setup>
// 页面绑定数据
<script>

 

3、定义一个Store用来缓存需要被缓存的页面集合

keepAliveStore.ts

import { defineStore } from "pinia";

export interface KeepAliveState {
  keepAliveComponents: Array<any>;
}

export const keepAliveStore = defineStore("keepAlive", {
    
  state: (): KeepAliveState => {
    return {
      keepAliveComponents: []
    };
  },

  getters: {
    getKeepAliveComponents(state) {
      return state.keepAliveComponents;
    }
  },

  actions: {
      
    // 加入到缓存队列
    setKeepAlive(component: any) {
      if (!this.keepAliveComponents.includes(component)) {
        this.keepAliveComponents.push(component);
      }
    },

    // 从缓存队列移除
    removeKeepAlive(component: any) {
      const index = this.keepAliveComponents.indexOf(component);
      if (index !== -1) {
        this.keepAliveComponents.splice(index, 1);
      }
    }

  }
});

4、路由守卫处理:在路由进入之前读取Meta扩展数据,如果配置了缓存,就加入到缓存队列中;在路由离开之前判断目标路由的Meta扩展数据,如果该页面与配置的来源页面不匹配,则将目标路由从缓存队列中移除

router/index.ts

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes
});

// --- beforeRouter --- //
router.beforeEach((to, _from, next) => {

  const { KeepAliveStore } = usePiniaStore();
  const meta = to.meta || {};

  // 加入缓存队列
  if (meta.keepAlive) {
    KeepAliveStore.setKeepAlive(to.name);
  }  

  // 做一些其他的事情
});

// ---afterRouter --- //
router.afterEach((to, from) => {

  const { KeepAliveStore } = usePiniaStore();

  // 如果配置了目标缓存,即:目标页面不在目标缓存中,移除当前页面缓存
  if (from.meta.keepAlivePages) {
    if (from.meta.keepAlivePages.indexOf(to.name as string) == -1) {
      KeepAliveStore.removeKeepAlive(from.name);
    }
  }

  // 做一些其他的事情
});

 

5、keep-alive组件的使用:取出缓存队列中的集合,配置给include属性,keep-alive组件便能把配置的路由页面给缓存起来了;同时也可以设置max最大缓存数,避免缓存太多导致性能下降

RouterView.vue

<template>
  <router-view v-slot="{ Component }">
    <transition name="fade" mode="out-in" appear>
      <keep-alive :include="keepAliveComponents" :max="10">
        <component :is="Component" />
      </keep-alive>
    </transition>
  </router-view>
</template>

<script lang="ts" setup>
import { usePiniaStore } from "@/store";
    
const { KeepAliveStore } = usePiniaStore();
const keepAliveComponents = KeepAliveStore.getKeepAliveComponents;
</script>

 

热门相关:首席的独宠新娘   薄先生,情不由己   刺客之王   霸皇纪   大神你人设崩了