全网最细!Vue3实现路由缓存~

本文介绍了如何在Vue3应用中设置全局缓存策略,包括使用Pinia管理缓存数据,设置路由守卫确保组件缓存,以及通过formatComponentInstance函数处理组件名称,以避免同一组件因路由参数变化而重复渲染。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、设置缓存对应的数据

  1. 需要在全局状态管理中,或者当前组件中添加数据(本次演示在全局状态管理中,使用的是 pinia)

    const coreStore = defineStore('coreStore', {
        state () {
            return {
                // 缓存页面路由数组及组件
                cacheRoutes: [],
                includeComs: [],
                cacheComs: new Map()
            }
        },
        actions: {
            setCacheRoute (route: { fullPath: string, name: string }): void {
                this.cacheRoutes.push(route)
            }
        },
    })
    
  2. 在根组件 App.vue 中引入进来

    const store = costore();
    const { cacheRoutes, includeComs, cacheComs } = store
    

2、路由生命周期设置

在 App.vue 组件中,需要设置路由进入前的守卫函数,用于将对应组件进行缓存:

import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

router.beforeEach((to, from, next) => {
    // 1 判断内部是否已有改缓存页面
    const bol = cacheRoutes.some(v => v.fullPath === to.fullPath)
    // 2 如果不存在,则存进缓存标签数组中
    !bol && cacheRoutes.push({ fullPath: to.fullPath, name: to.meta.title })
    // 3 缓存组件对应的路由名称
    !includeComs.includes(to.fullPath) && includeComs.push(to.fullPath);
    next()
})

3、将路由组件进行缓存

这个是 Vue3 的写法,不适用与 Vue2

<router-view v-slot="{ Component }">
    <keep-alive :include="includeComs" style="margin-left: 16px;">
        <component :is="formatComponentInstance(Component, $route)" :key="$route.fullPath" />
    </keep-alive>
</router-view>

4、formatComponentInstance

这是最重要的一个函数,因为缓存组件的时候 keep-alive 会根据组件名称进行缓存,假设现在有个 A.vue 组件(名称为 A,如果不使用选项式写法,Vue3默认将组件名称作为组件的 name)

在访问 A?a=1A?a=2 两个路径的时候,会导致访问的都是已缓存的组件,不会重新进行挂载渲染

因此需要该函数保证不同路径下,即使组件相同,也能进行重新挂载和缓存

import { compile, h, nextTick, onMounted, ref, watch } from "vue";

// 显示组件时,替换组件 name,解决同个组件路由不一致问题
const formatComponentInstance = (component, route) => {
    let wrapper;
    if (component) {
        const wrapperName = route.fullPath
        if (cacheComs.has(wrapperName)) {
            wrapper = cacheComs.get(wrapperName);
        } else {
            wrapper = {
                name: wrapperName,
                render() {
                    return h(component);
                },
            }
            cacheComs.set(wrapperName, wrapper);
        }
    }
    return h(wrapper);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值