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

相关推荐

  1. VUE3定义控制keep-alive缓存

    2024-01-16 15:24:04       34 阅读
  2. Vue-组件缓存-keep-alive

    2024-01-16 15:24:04       31 阅读
  3. Vue3中使用缓存组件keep-alive vue3缓存组件

    2024-01-16 15:24:04       41 阅读
  4. vue3 keep-alive include失效问题

    2024-01-16 15:24:04       12 阅读
  5. Vue中的keep-alive缓存组件的理解

    2024-01-16 15:24:04       35 阅读
  6. Vue中的keep-alive缓存组件的理解

    2024-01-16 15:24:04       27 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-16 15:24:04       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-16 15:24:04       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-16 15:24:04       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-16 15:24:04       18 阅读

热门阅读

  1. chrome 307状态码

    2024-01-16 15:24:04       35 阅读
  2. 开发版本Alpha,Beta等详解适用多个领域的版本解释

    2024-01-16 15:24:04       30 阅读
  3. 「HDLBits题解」Multiplexers

    2024-01-16 15:24:04       33 阅读
  4. 期刊会议机构区别

    2024-01-16 15:24:04       37 阅读
  5. 超形象图解Python NumPy

    2024-01-16 15:24:04       36 阅读
  6. 北京多家公司因数据泄露风险被罚

    2024-01-16 15:24:04       34 阅读
  7. 智慧校园云桌面解决方案简述

    2024-01-16 15:24:04       36 阅读
  8. 2024 CKA 题库 | 10、创建 PV

    2024-01-16 15:24:04       36 阅读
  9. Linux篇之Centos中将系统时间设置为本地时间

    2024-01-16 15:24:04       38 阅读
  10. 嵌入式工程师必须掌握的几种系统架构

    2024-01-16 15:24:04       31 阅读