我使用vuejs3+typescript构建后台管理系统,并使用keep-alive来缓存页面。如何获得当前缓存的组件?
<keep-alive>
组件仅在开发版本中将其缓存公开为__v_cache
。您可以在<keep-alive>
上使用模板ref,并从其内部实例($
)读取__v_cache
:
<template>
<button @click="logKeepAliveCache">Log keep-alive cache</button>
<router-view v-slot="{ Component }">
<keep-alive ref="keepAlive">
<component :is="Component" />
</keep-alive>
</router-view>
</template>
<script setup>
import { ref } from 'vue'
const keepAlive = ref()
const logKeepAliveCache = () => {
// The cache is a `Map`, where the entry keys are
// metadata about the component's file, and the
// filename is stored in `__file`.
console.log([...keepAlive.value.$?.__v_cache.keys()].map((x) => x.__file))
}
</script>
注意__v_cache
在生产版本中不可用。