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

相关推荐
q***31142 分钟前
【Springboot3+vue3】从零到一搭建Springboot3+vue3前后端分离项目之后端环境搭建
android·前端·后端
q***12536 分钟前
Plugin ‘org.springframework.bootspring-boot-maven-plugin‘ not found(已解决)
java·前端·maven
攻城狮CSU7 分钟前
C# 异步方法
开发语言·前端·c#
tyro曹仓舒7 分钟前
干了10年前端,才学会使用IntersectionObserver
前端·javascript
S***y39628 分钟前
前端微前端框架对比,qiankun与icestark
前端·前端框架
Wect39 分钟前
学习React-DnD:实现多任务项拖拽-useDrop处理
前端·react.js
Mintopia1 小时前
Trae Coding - 「Excel 秒变海报」—— 上传 CSV,一句话生成可打印信息图。
前端·人工智能·trae
晴殇i1 小时前
CSS 相对颜色:告别 180 个颜色变量的设计系统噩梦
前端·css
MegatronKing1 小时前
Reqable 3.0版本云同步的实践过程
前端·后端·测试
李剑一1 小时前
我用Trae生成了一个Echarts 3D柱状图的Demo
前端·vue.js·trae