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

相关推荐
时光足迹2 分钟前
Tiptap 简单编辑器模版
前端·javascript·react.js
吴声子夜歌13 分钟前
Vue3——使用Mock.js
javascript·vue·mock.js
JSLove16 分钟前
nginx入门
前端·nginx
时光足迹17 分钟前
ThreeJS之GUI控制器
前端·javascript·three.js
时光足迹18 分钟前
Tiptap编辑器
前端·javascript·react.js
im_AMBER19 分钟前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵
时光足迹21 分钟前
电子书阅读器之笔记高亮(跨段处理)
前端·javascript·react.js
Dabei24 分钟前
Android 副屏(Virtual Display)创建与悬浮窗画中画显示实战
前端·架构
RONIN28 分钟前
mock模拟后端,生成伪数据接口
vue.js