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

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

相关推荐
明月_清风4 小时前
Deno 终局来了:从挑战 Node 到被 Cloudflare 收编
前端·后端·node.js
Csvn5 小时前
框架性能优化
前端
雪芽蓝域zzs7 小时前
第 5 节:Marker 点击弹出 InfoWindow 信息窗口
vue.js
回眸&啤酒鸭7 小时前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户69371750013847 小时前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员7 小时前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子7 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒7 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend8 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
小宋10219 小时前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互