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

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

相关推荐
C澒6 分钟前
前端整洁架构(Clean Architecture)实战解析:从理论到 Todo 项目落地
前端·架构·系统架构·前端框架
C澒12 分钟前
Remesh 框架详解:基于 CQRS 的前端领域驱动设计方案
前端·架构·前端框架·状态模式
Charlie_lll15 分钟前
学习Three.js–雪花
前端·three.js
onebyte8bits32 分钟前
前端国际化(i18n)体系设计与工程化落地
前端·国际化·i18n·工程化
C澒41 分钟前
前端分层架构实战:DDD 与 Clean Architecture 在大型业务系统中的落地路径与项目实践
前端·架构·系统架构·前端框架
BestSongC1 小时前
行人摔倒检测系统 - 前端文档(1)
前端·人工智能·目标检测
0思必得01 小时前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
Misnice1 小时前
Webpack、Vite、Rsbuild区别
前端·webpack·node.js
青茶3601 小时前
php怎么实现订单接口状态轮询(二)
前端·php·接口
大橙子额2 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js