Vue3 对跳转 同一路由传入不同参数的页面分别进行缓存

1:使用场景

从列表页跳转至不同的详情页面,对这些详情页面分别进行缓存

2:核心代码

2.1: 配置路由文件

在路由文件里对需要进行缓存的路由对象添加meta 属性

// 需要缓存的详情页面路由

{

name: detail,

path: '/myRouter/detail', // 路径

component: () => import('../views/abc/detail.vue'),

meta: {

keepAlive: true, // 是否被缓存

},

},

2.2: app页面增加缓存逻辑

<template>

<el-config-provider :locale="locale">

<!-- 有条件的进行缓存 -->

<transition mode="out-in" name="fade">

<router-view v-slot="{ Component }">

<keep-alive :include="includeList">

<component :is="wrap(route?.name , route.query, Component)" :key="route.fullPath" />

</keep-alive>

</router-view>

</transition>

</el-config-provider>

</template>

wrap 方法

javascript 复制代码
    const wrapperMap = new Map();

    const wrap = (name:any, query:any, component:any) => {
      let wrapper;
       let wrapperName;
      if(query.catchName){
           wrapperName = name + '-' + query.catchName;
      }else {
          wrapperName  = name;
      }
    
      if (wrapperMap.has(wrapperName)) {
        wrapper = wrapperMap.get(wrapperName);
      } else {
        wrapper = {

          name: wrapperName,

          render() {
            return h('div', { className: 'vaf-page-wrapper' }, component);
          },

        };

        wrapperMap.set(wrapperName, wrapper);
      }

      return h(wrapper);
    };

watch 监听对于route.query 是否存在catchName 参数的路由分别进行缓存

javascript 复制代码
// 监听路由,判断页面是否需要缓存
    watch(
      () => route,
      (newVal: any, oldVal) => {
       
        if (newVal.query?.catchName) {
          if (newVal.meta.keepAlive && !state.includeList.includes(newVal.name + '-' + newVal.query?.catchName)) {
            state.includeList.push(newVal.name + '-' + newVal.query?.catchName);
          }
        } else if (newVal.meta.keepAlive && !state.includeList.includes(newVal.name)) {
          state.includeList.push(newVal.name);
        }
      },
      {
        deep: true, // 开启深度监听
      },
    );

2.3: 在列表页面的查看点击方法中配置路由添加query 传参 catchName

注:上面为核心代码逻辑,需要根据实际情况进行调整。

相关推荐
万少6 分钟前
HarmonyOS Next 弹窗系列教程(3)
前端·harmonyos·客户端
七灵微1 小时前
【后端】单点登录
服务器·前端
持久的棒棒君5 小时前
npm安装electron下载太慢,导致报错
前端·electron·npm
渔舟唱晚@7 小时前
大模型数据流处理实战:Vue+NDJSON的Markdown安全渲染架构
vue.js·大模型·数据流
crary,记忆7 小时前
Angular微前端架构:Module Federation + ngx-build-plus (Webpack)
前端·webpack·angular·angular.js
漂流瓶jz8 小时前
让数据"流动"起来!Node.js实现流式渲染/流式传输与背后的HTTP原理
前端·javascript·node.js
SamHou08 小时前
手把手 CSS 盒子模型——从零开始的奶奶级 Web 开发教程2
前端·css·web
我不吃饼干8 小时前
从 Vue3 源码中了解你所不知道的 never
前端·typescript
开航母的李大8 小时前
【中间件】Web服务、消息队列、缓存与微服务治理:Nginx、Kafka、Redis、Nacos 详解
前端·redis·nginx·缓存·微服务·kafka
Bruk.Liu8 小时前
《Minio 分片上传实现(基于Spring Boot)》
前端·spring boot·minio