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

相关推荐
GIS之路5 分钟前
GDAL 创建矢量图层的两种方式
前端
2501_9481953444 分钟前
RN for OpenHarmony英雄联盟助手App实战:符文配置实现
javascript·react native·react.js
小目标一个亿1 小时前
Windows平台Nginx配置web账号密码验证
linux·前端·nginx
rocky1911 小时前
网页版时钟
前端·javascript·html
Aotman_1 小时前
Element-UI Message Box弹窗 使用$confirm方法自定义模版内容,修改默认样式
linux·运维·前端
计算机程序设计小李同学1 小时前
基于SSM框架的动画制作及分享网站设计
java·前端·后端·学习·ssm
一只小阿乐2 小时前
vue-web端实现图片懒加载的方
前端·javascript·vue.js
+VX:Fegn08952 小时前
计算机毕业设计|基于springboot + vue小型房屋租赁系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
牛马1112 小时前
Flutter 多语言
前端·flutter
by————组态2 小时前
集成详细说明
前端·物联网·信息可视化·组态·组态软件