VUE3,自定义控制keep-alive缓存

安装插件

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)

}

}

})

在进入别的一级菜单前

clearKeepAliveCache()

相关推荐
万少5 分钟前
可可图片编辑 HarmonyOS(5)滤镜效果
前端
Yvonne爱编码36 分钟前
后端编程开发路径:从入门到精通的系统性探索
java·前端·后端·python·sql·go
GIS之路2 小时前
GDAL 读取遥感影像数据
前端
wow_DG2 小时前
【Vue2 ✨】Vue2 入门之旅 · 进阶篇(九):Vue2 性能优化
javascript·vue.js·性能优化
一 乐2 小时前
美食分享|基于Springboot和vue的地方美食分享网站系统设计与实现(源码+数据库+文档)
java·vue.js·spring boot·论文·毕设·美食·地方美食分享网站系统
IT_陈寒3 小时前
Spring Boot 3.2 新特性全解析:这5个性能优化点让你的应用提速50%!
前端·人工智能·后端
携欢3 小时前
PortSwigger靶场之Stored DOM XSS通关秘籍
前端·xss
GDAL3 小时前
Knockout-ES5 入门教程
javascript·knockout
正义的大古3 小时前
OpenLayers数据源集成 -- 章节八:天地图集成详解
开发语言·javascript·ecmascript·openlayers
LDM>W<3 小时前
Electron下载失败
前端·javascript·electron