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

相关推荐
这个昵称也不能用吗?3 分钟前
react-native搭建开发环境过程记录
前端·react native·cocoapods
hy_花花4 分钟前
Vue3.4之defineModel的用法
前端·vue.js
DataFunTalk18 分钟前
Foundation Agent:深度赋能AI4DATA
前端·后端·算法
hboot20 分钟前
rust 全栈应用框架dioxus
前端·rust·全栈
我是仙女你信不信25 分钟前
生成pdf并下载
前端·javascript·vue.js
少糖研究所25 分钟前
记一次Web Worker的使用
前端·性能优化
乔乔不姓乔呀27 分钟前
pc 和大屏如何适配
前端
speedoooo38 分钟前
新晋前端框架技术:小程序容器与SuperApp构建
前端·小程序·前端框架·web app
vvilkim1 小时前
React 组件类型详解:类组件 vs. 函数组件
前端·javascript·react.js
猫了个咪丶1 小时前
一文教你搞懂如何消除异步函数的传染性
前端