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

相关推荐
袋鱼不重31 分钟前
我的神奇同事,AI 用多了居然写了个 Open In Codex
前端·后端·ai编程
竹林81836 分钟前
Web3表单签名验证:我用 wagmi 和 ethers 给 DApp 加了一个“免密登录”,踩坑记录全在这了
javascript
用户69903048487538 分钟前
try catch使用场景 处理同步代码错误兼容用的
javascript·uni-app
雪碧聊技术41 分钟前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
Fireworks1 小时前
深入vue3源码解读 -- 1、响应式的基础概念
前端
程序员黑豆1 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
hunterandroid1 小时前
文件存储:内部存储与外部存储
前端
VidDown1 小时前
VidDown 工具站:免费、本地优先的开发者工具箱
javascript·编辑器·音视频·视频编解码·视频
NorBugs2 小时前
飞机大战 Low 版 (Made in AI)
前端
angerdream2 小时前
Android手把手编写儿童手机远程监控App之agentweb如何实现全屏
前端