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

相关推荐
用户49394095229355 小时前
Function.prototype.bind实现
前端
用户841794814565 小时前
vue 甘特图 vxe-gantt 任务里程碑和依赖线的使用
vue.js
AAA阿giao5 小时前
Vue3 调用 Coze 工作流:从上传宠物照到生成冰球明星的完整技术解析
前端·vue.js·coze
异界蜉蝣5 小时前
React Fiber架构:Diff算法的演进
前端·react.js·前端框架
追梦_life5 小时前
localStorage使用不止于getItem、setItem、removeItem
前端·javascript
全栈陈序员5 小时前
请描述下你对 Vue 生命周期的理解?在 `created` 和 `mounted` 中请求数据有什么区别?
前端·javascript·vue.js·学习·前端框架
无限大65 小时前
用三行代码实现圣诞树?别逗了!让我们来真的
前端·javascript
init_23615 小时前
label-route-capability
服务器·前端·网络
拉姆哥的小屋5 小时前
深度剖析SentiWordNet情感词典:155,287单词的情感世界
前端·javascript·easyui
T___T5 小时前
从 0 搭建 React 待办应用:状态管理、副作用与双向绑定模拟
前端·react.js·面试