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

相关推荐
蓝胖子的多啦A梦3 分钟前
npm : 无法加载文件 C:\Program Files\nodejs\npm.ps1,因为在此系统上禁止运行脚
前端·npm·node.js
LinCC75 分钟前
在Vite中构建项目出错-Top-level await is not available in the configured target environme
前端
咪库咪库咪5 分钟前
js的浅拷贝与深拷贝
javascript
幸福的猪在江湖6 分钟前
第一章:变量筑基 - 内力根基修炼法
javascript
Ryan今天学习了吗6 分钟前
💥不说废话,带你使用原生 JS + HTML 实现超丝滑拖拽排序效果
javascript·html
用户882093216676 分钟前
如何优雅拆分一个充斥十几种逻辑的 SDK 回调函数?
前端
Momoly088 分钟前
vue3+el-table 利用插槽自定义数据样式
前端·javascript·vue.js
多啦C梦a8 分钟前
从 React 初体验到数据驱动的界面开发:一步步解析 Todo List 组件
javascript·react.js
唯有选择8 分钟前
让你的应用界面好看的基石:Flutter主题Theme使用和扩展自定义字段
前端·flutter
山有木兮木有枝_8 分钟前
告别布局间隙:浮动(float)在网页排版中的高阶应用
前端