vue3 keep-alive 自定义key缓存

Posted on 2022-03-25 12:38  荆楚尬聊娃  阅读(390)  评论(0编辑  收藏  举报
 1 <template>
 2   <router-view v-slot="{ Component }">
 3     <keep-alive v-for="cache in cacheKeys" :key="cache">
 4       <component v-if="cache === key" :key="key" :is="Component" />
 5     </keep-alive>
 6     <component v-if="!keepAlive" :key="key" :is="Component" />
 7   </router-view>
 8 </template>
 9 
10 <script lang="ts" setup>
11 // 工具
12 import { computed } from "vue";
13 import { useStore } from "vuex";
14 import { useRoute } from "vue-router";
15 
16 // 工具实例
17 const store = useStore();
18 const route = useRoute();
19 
20 // 键值
21 const key = computed(() => {
22   const value = route.meta.key;
23   return typeof value === "function" ? value(route) : (value || route.fullPath);
24 });
25 
26 // 缓存键列表
27 const cacheKeys = computed(() => {
28   return store.getters["tabs/cacheKeys"] as string[];
29 });
30 
31 // 是否缓存
32 const keepAlive = computed(() => {
33   return cacheKeys.value.includes(key.value);
34 });
35 </script>