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

相关推荐
web打印社区21 小时前
Vue3 发票静默打印,我这边能跑通的一版
前端·javascript·vue.js·chrome·electron
嘟哩DuliDuli21 小时前
创作 Agent 的任务状态该如何保存
android·java·javascript
lemon_sjdk21 小时前
JavaScript 常用关键字全解析
开发语言·javascript·ecmascript
妖孽白小白1 天前
el-select的内容续写实现
前端·vue.js·elementui
不可能片场1 天前
Electron 主进程热补丁:单行 JS 安全打法
前端·electron
梨想橙汁1 天前
Pinia 状态管理实战:定义 Store、修改数据、模块拆分
前端·vue.js
高申航1 天前
Vue 3 + DYMO Connect Framework 实战:从标签模板到打印服务的完整实现
前端·javascript·vue.js
梨想橙汁1 天前
Vue3 组件开发:生命周期钩子,组件之间通信全方案
前端·vue.js
雪芽蓝域zzs1 天前
分页组件 + el-config-provider 中文国际化 + 靠右布局
前端·javascript·vue.js
恋猫de小郭1 天前
iPhone Duo 适配详解,需要改变的不止是布局模型
前端·flutter·ios