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

相关推荐
AI_56788 分钟前
Webpack性能优化终极指南:4步实现闪电打包
前端·webpack·性能优化
xuehuayu.cn26 分钟前
js es6 class 类中的值是异步赋值, 子类中如何获取这个值?
javascript·es6
威风的虫30 分钟前
ES6 数组方法:告别循环,拥抱函数式编程
开发语言·前端·javascript
小杨快跑~33 分钟前
ES6 Promise:告别回调地狱的异步编程革命
前端·javascript·ecmascript·es6
linweidong40 分钟前
VIVO前端面试题及参考答案
前端·跨域·localstorage·重绘·浏览器兼容·git管理·前端重构
有意义41 分钟前
从零搭建:json-server+Bootstrap+OpenAI 全栈 AI 小项目
前端·后端·llm
温宇飞42 分钟前
CCState:为大型 Web 应用设计的状态管理库
前端
r0ad1 小时前
读诗的时候我却使用了自己研发的Chrome元素截图插件
前端·javascript·chrome
IT_陈寒2 小时前
React性能优化实战:这5个Hooks技巧让我的应用快了40%
前端·人工智能·后端
江天澄2 小时前
HTML5 中常用的语义化标签及其简要说明
前端·html·html5