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

相关推荐
可观测性用观测云19 小时前
前端错误可观测最佳实践
前端
恋猫de小郭19 小时前
Android 将强制应用使用主题图标,你怎么看?
android·前端·flutter
一枚前端小能手20 小时前
「周更第3期」实用JS库推荐:Lodash
前端·javascript
艾小码20 小时前
Vue组件到底怎么定义?全局注册和局部注册,我踩过的坑你别再踩了!
前端·javascript·vue.js
Cyan_RA920 小时前
计算机网络面试题 — TCP连接如何确保可靠性?
前端·后端·面试
谢尔登20 小时前
【CSS】层叠上下文和z-index
前端·css
鹏多多20 小时前
前端复制功能的高效解决方案:copy-to-clipboard详解
前端·javascript
AryaNimbus20 小时前
你不知道的 Cursor系列(三):再也不用死记硬背 Linux 命令,终端 Cmd+K 来帮你!
前端·ai编程·cursor
uhakadotcom20 小时前
Rollup 从0到1:TypeScript打包完全指南
前端·javascript·面试
Mintopia20 小时前
实时语音转写 + AIGC:Web 端智能交互的技术链路
前端·javascript·aigc