vue3页面路由缓存的一种方法

app.vue

js 复制代码
<template>
  <div id="app">
    <router-view v-slot="{ Component }">
      <keep-alive>
        <component :is="Component" v-if="$route.meta.keepAlive" />
      </keep-alive>
      <component :is="Component" v-if="!$route.meta.keepAlive" />
    </router-view>
  </div>
</template>

<script setup>
</script>

router.js

js 复制代码
 {
    path: '/MPcard/MPcard',
    name: 'MPcard',
    component: () => import('../views/MPcard/MPcard.vue'),
    meta: { title: "名片查询",keepAlive:true},
  },
  {
    path: '/MPcard/MPecharts',
    name: 'MPecharts',
    component: () => import('../views/MPcard/MPecharts.vue'),
    meta: { title: "名片图表" },
  },
  {
    path: '/MPechartsZX/MPechartsZX',
    name: 'MPechartsZX',
    component: () => import('../views/MPcard/MPechartsZX.vue'),
    meta: { title: "名片折线图表" },
  },

从 名片查询页面进入到名片图表或着名片折线图表页面,返回的名片查询页面是不需要刷新的,但是从其它页面进来是需要刷新的

页面

js 复制代码
import { ref, onMounted, nextTick, onActivated, onDeactivated } from "vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
const chushih=()=>{
  //这里就发送请求
}
onMounted(() => {
  console.log('刷新了')
  chushih();
});
const refreshFlag=ref('需要刷新')
onBeforeRouteLeave((to, from, next)=>{
  const element = document.getElementById('mainContent').scrollTop
  console.log('前往-to',to)
  console.log('当前也-from',from)
  console.log('离开了的时候当前页面的ID是mainContent的滚动高度',element)
  data.value.scrollTop=element
  // 这个是 进入数组里面的页面,需要缓存的
  let array=['/MPcard/MPecharts','/MPechartsZX/MPechartsZX']  //从这几个页面返回的不需要刷新
  if(array.includes(to.path)){
    refreshFlag.value='不需要刷新'
  }else{
    refreshFlag.value='需要刷新'
  }
  next()
})
onActivated(()=>{
  // console.log('回来了',refreshFlag.value)
  if(refreshFlag.value=='需要刷新'){
    chushih()
  }else{
    document.getElementById('mainContent').scrollTop=data.value.scrollTop
  }
})
相关推荐
2601_9583529011 小时前
A-59U 仅 37mm 却集成 USB + 双波束?
前端·回声消除·语音模块·降噪处理·降噪消回音
泯泷17 小时前
那段文字是谁删的?Yjs 14 正式版之前,一套删除归属方案的实现与边界
前端·javascript·算法
HanhahnaH19 小时前
Redis单线程和Tair多线程架构设计对比
分布式·缓存
野槐20 小时前
前端项目优化(有了我,会发生...)
前端
aa小小20 小时前
【无标题】
前端
计算机魔术师21 小时前
还在单线程跟 AI 聊天?Claude Code 并行多会话让你一个人干三个人的活
前端
志尊宝21 小时前
Vue3 零基础每日笔记(038):亲手封装 useDebounceFn 与 useThrottleFn——高频事件的流量阀
前端·javascript·vue·html·vue3
JavaGuide21 小时前
对标 MinIO!全新一代分布式文件系统正式发布
前端·后端
风骏时光牛马21 小时前
AI驱动自动化业务工作流搭建实践
前端
码云之上1 天前
Skill 里的脚本终于能跑了,星悟接 CubeSandbox 的纪实
前端·人工智能·前端框架