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

相关推荐
前端小趴菜0531 分钟前
React-React.memo-props比较机制
前端·javascript·react.js
摸鱼仙人~2 小时前
styled-components:现代React样式解决方案
前端·react.js·前端框架
sasaraku.2 小时前
serviceWorker缓存资源
前端
RadiumAg3 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo3 小时前
ES6笔记2
开发语言·前端·javascript
yanlele3 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
中微子5 小时前
React状态管理最佳实践
前端
烛阴5 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
中微子5 小时前
JavaScript 事件与 React 合成事件完全指南:从入门到精通
前端
Hexene...5 小时前
【前端Vue】如何实现echarts图表根据父元素宽度自适应大小
前端·vue.js·echarts