vue3配置页面缓存

56 阅读1分钟

layout页面,使用route.fullPath+history.state.posiition对页面做唯一索引;

<template>
  <RouterView>
    <template #default="{ Component, route }">
      <keep-alive :include="getCaches" :max="5">
        <component :is="Component" :key="getKeepAliveKey(route)" />
      </keep-alive>
    </template>
  </RouterView>
</template>

<script lang="ts" setup>
  import { reactive } from 'vue';

  import { RouteLocationNormalizedLoadedGeneric } from 'vue-router';

  const getCaches = reactive(['PageA']);

  const getKeepAliveKey = (route: RouteLocationNormalizedLoadedGeneric) => {
    const { fullPath } = route;
    return `Cache-${history?.state?.position ?? 0}-${fullPath}`;
  };
</script>

路由页面,需要定义name

<script lang="ts" setup>
  defineOptions({ name: 'PageA' });
</script>

<template>
  <div>
  </div>
</template>