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

相关推荐
tedcloud1234 小时前
RTK部署教程:构建稳定的AI Workflow环境
服务器·javascript·人工智能·typescript·ocr
ZC跨境爬虫5 小时前
跟着 MDN 学CSS day_16:(深入掌握背景与边框的艺术)
前端·css·ui·html·tensorflow
愚者Pro7 小时前
Flutter Widget组件学习(专为 Uniapp 转 Flutter 定制)
vue.js·学习·flutter·uni-app
道里7 小时前
花了 5 万刀用 AI 写代码之后,这是我的全部经验
前端·人工智能
Royzst8 小时前
xml知识点
java·服务器·前端
IT_陈寒8 小时前
React useEffect闭包陷阱差点把我整失业了
前端·人工智能·后端
kyriewen9 小时前
推行AI写代码一年后,Code Review变成了新的加班理由
前端·ai编程·cursor
前端环境观察室9 小时前
给 Agent Browser Workflow 加一层可观测性:Trace、Snapshot 和 Review Queue
前端
柒瑞9 小时前
Superpowers结合Claude code浅实战
前端
Nian.Baikal10 小时前
从零搭建离线地图服务:Nginx + Cesium/Leaflet 实战指南
运维·前端·nginx