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

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

相关推荐
Jackson__13 分钟前
为什么 Agent 越聊越慢?聊聊 Context(上下文)管理
前端·agent·ai编程
KaMeidebaby28 分钟前
卡梅德生物技术快报|抗体合成:多肽抗体合成工程化方案:Nsp2 保守肽多抗制备与多维度验证
前端·网络·数据库·人工智能·算法
青禾网络34 分钟前
前端做音画匹配这件事,我从"随机塞"到"AI 自动对齐"
前端·github
仙人球部落1 小时前
-python-LangGraph框架(3-31-LangGraph 「合并式状态管理」的原理与实践)
开发语言·javascript·python
2601_963771371 小时前
Hardening Enterprise WordPress Sites Against REST API Leaks and Bad Headers
前端·windows·word·php
蓝银草同学1 小时前
Stream 实战:博客列表排序、过滤与分页(AI 辅助学习 Java 8)
java·前端·后端
2601_957190902 小时前
飞行影院安装施工指南:场地、动感系统与影片内容配套
大数据·前端·人工智能
爱折腾的小黑牛2 小时前
简记往来批量录入功能的实现:从文本到结构化数据
前端·算法
sunfdf2 小时前
Next.js 新手从零部署到首跑实战指南
开发语言·javascript·ecmascript
YHHLAI2 小时前
Agent 智能体开发实战 · 第六课:MCP 协议 —— 让 Agent 跨进程调用工具
前端·人工智能