安装插件
npm install vite-plugin-vue-setup-extend --save
在vite.config.ts中
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
.....
plugins:[
vue(),
VueSetupExtend(),
.....
]
useKeepalive.ts
import { ref } from "vue"
export const includes = ref<string[]>([]);
// 增加缓存export function addKeepAliveCache(name: string) {
if (includes.value.find(item => item === name)) return;
includes.value.push(name);
}
// 移除缓存
export function removeKeepAliveCache(name: string) {
const index: number | undefined | null = includes.value.findIndex(item => item === name)
if([null, undefined].includes(index)) return
includes.value.splice(index, 1);
}
// 清空缓存
export function clearKeepAliveCache() {
includes.value = [];
}
App.vue
<router-view v-slot="{ Component }">
<keep-alive :include="includes">
<component :key="route.name || route.path" :is="Component" />
</keep-alive>
</router-view>
在路由钩子中:
router.afterEach((to) => {
if (to.meta?.keepAlive) {
const matched = router.currentRoute.value.matched ?? []
const instance = matched.find((instan: any) => instan.path === to.path)
// 读取路由组件实例的name属性
const name: string = String(instance?.components?.default?.name || '');
if (name) {
addKeepAliveCache(name)
}
}
})
在进入别的一级菜单前文章来源:https://www.toymoban.com/news/detail-805494.html
clearKeepAliveCache()文章来源地址https://www.toymoban.com/news/detail-805494.html
到了这里,关于VUE3,自定义控制keep-alive缓存的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!