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

相关推荐
Highcharts.js31 分钟前
什么是向量图表?如何用 Highcharts 快速创建一个笛卡尔坐标图/矢量图?
javascript·开发文档·highcharts·图表开发·向量图·矢量图表·笛卡尔坐标图
NEXT061 小时前
React 闭包陷阱深度解析:从词法作用域到快照渲染
前端·react.js·面试
脱离语言1 小时前
Jeecg3.8.2 前端经验汇总
开发语言·前端·javascript
NEXT062 小时前
useMemo 与 useCallback 的原理与最佳实践
前端·javascript·react.js
小爱丨同学2 小时前
React-Context用法汇总 +注意点
前端·javascript·react.js
徐同保3 小时前
python如何手动抛出异常
java·前端·python
极客小云3 小时前
【实时更新 | 2026年国内可用的npm镜像源/加速器配置大全(附测速方法)】
前端·npm·node.js
半兽先生3 小时前
告别 AI 乱写 Vue!用 vue-skills 构建前端智能编码标准
前端·vue.js·人工智能
木易 士心3 小时前
ESLint 全指南:从原理到实践,构建高质量的 JavaScript/TypeScript 代码
javascript·ubuntu·typescript
前端达人4 小时前
都2026年了,还在用Options API?Vue组合式API才是你该掌握的“正确姿势“
前端·javascript·vue.js·前端框架·ecmascript