本文介绍: / 读取路由组件实例的name属性。在vite.config.ts中。在进入别的一级菜单前。

安装插件

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

原文地址:https://blog.csdn.net/HuaiCheng9067/article/details/135623131

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_56828.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注