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()

相关推荐
cz追天之路18 小时前
华为机考--- 字符串最后一个单词的长度
javascript·css·华为·less
Light6018 小时前
CSS逻辑革命:原生if()函数如何重塑我们的样式编写思维
前端·css·响应式设计·组件化开发·css if函数·声明式ui·现代css
蜡笔小嘟18 小时前
宝塔安装dify,更新最新版本--代码版
前端·ai编程·dify
Irene199119 小时前
Vue:useSlots 和 useAttrs 深度解析
vue.js·useslots·useattrs
ModyQyW19 小时前
HBuilderX 4.87 无法正常读取 macOS 环境配置的解决方案
前端·uni-app
bitbitDown19 小时前
我的2025年终总结
前端
五颜六色的黑19 小时前
vue3+elementPlus实现循环列表内容超出时展开收起功能
前端·javascript·vue.js
wscats20 小时前
Markdown 编辑器技术调研
前端·人工智能·markdown
EnoYao20 小时前
Markdown 编辑器技术调研
前端·javascript·人工智能
JIngJaneIL21 小时前
基于java+ vue医院管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot