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

相关推荐
Coding_Doggy18 分钟前
链盾shieldchain | 项目管理、DID操作、DID密钥更新消息定时提醒
java·服务器·前端
用户214118326360230 分钟前
dify案例分享-国内首发!手把手教你用Dify调用Nano Banana2AI画图
前端
wa的一声哭了38 分钟前
Webase部署Webase-Web在合约IDE页面一直转圈
linux·运维·服务器·前端·python·区块链·ssh
GISer_Jing42 分钟前
3D Cesium渲染架剖析
javascript·3d·webgl
han_43 分钟前
前端性能优化之CSS篇
前端·javascript·性能优化
k***85841 小时前
【SpringBoot】【log】 自定义logback日志配置
android·前端·后端
小满zs1 小时前
Next.js第十章(Proxy)
前端
JIngJaneIL1 小时前
汽车租赁|汽车管理|基于Java+vue的汽车租赁系统(源码+数据库+文档)
java·vue.js·spring boot·汽车·论文·毕设·汽车租赁
z***I3942 小时前
JavaScript爬虫应用案例
开发语言·javascript·爬虫
d***9352 小时前
Webpack、Vite区别知多少?
前端·webpack·node.js