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 方法

    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 参数的路由分别进行缓存

// 监听路由,判断页面是否需要缓存
    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

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

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 21:16:09       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 21:16:09       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 21:16:09       57 阅读
  4. Python语言-面向对象

    2024-07-12 21:16:09       68 阅读

热门阅读

  1. C#-反射

    C#-反射

    2024-07-12 21:16:09      15 阅读
  2. Codeforces Round #956 (Div. 2) and ByteRace 2024 A-C题解

    2024-07-12 21:16:09       23 阅读
  3. 科技与狠活

    2024-07-12 21:16:09       19 阅读
  4. 大语言模型系列-Transformer

    2024-07-12 21:16:09       21 阅读
  5. Git-Updates were rejected 解决

    2024-07-12 21:16:09       20 阅读
  6. 推荐系统中的冷启动问题及其解决方案

    2024-07-12 21:16:09       18 阅读
  7. vue在线预览excel、pdf、word文件

    2024-07-12 21:16:09       24 阅读
  8. 解决el-table表格没有横向滚动条

    2024-07-12 21:16:09       22 阅读
  9. PyTorch 1-深度学习

    2024-07-12 21:16:09       20 阅读