当前位置: 首页 > article >正文

vue3项目如何使用keepAlive?如何实现回退到这个页面时不刷新,跳转至这个页面时会刷新?

前言:

 页面A为首页面、页面B为设置了keepAlive的页面、页面C为新页面

问题:

只有第一次进入项目时,页面B加载一次,之后无论跳转还是切换都不刷新页面B了!!!o(╯□╰)o

要求:

只要是跳转至页面B,刷新B

只要是回退到页面B,不刷新B

解决:

加代码,App页面加入:key="$route.fullPath",跳转时加个实时时间的参数即可,代码如下:

一、如何给页面B设置keepAlive,保证这个页面不刷新

App.vue页面

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

router/index.js页面

import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL), // 使用 process.env.BASE_URL
  routes: [
   {
      path: '/B',
      name: 'B',
      component: () => import('../view/test/B.vue'),
      meta: { //只需要加入这个就行了
        keepAlive: true,
      },
    }
  ],
})

export default router

二、实现A跳转B时,刷新页面B

页面A:

<template>
  <button @click="jumpButton">A页面</button>
</template>
<script setup>
const wheelButton = () => {
    nextTick(() => { //等待路由加载完再跳转
        router.push({
        path: '/B',
        query: { reload: Date.now() } // reload 参数确保URL变化(使用keepalive时要求重新进入这个页面强制刷新)
  });
  });
}
</script>

这样就能实现,A跳转B刷新B,C回退B不会刷新B了~(* ̄︶ ̄)


http://www.kler.cn/a/589522.html

相关文章:

  • Redis主从集群和哨兵集群
  • CML(Current Mode Logic)电平详解
  • MyBatis XMLMapperBuilder 是如何解析 SQL 映射文件的? 它读取了哪些信息?
  • docker安装rabbitmq
  • pyyaml_include 2.x 版本使用说明
  • Spring Cloud Gateway 生产级实践:高可用 API 网关架构与流量治理解析
  • Linux应用软件编程(多任务:进程间通信)
  • Excel VBA实现智能合并重复元器件数据(型号去重+数量累加)
  • VSCode C/C++ 环境搭建指南
  • 云原生服务网格:微服务通信的神经中枢革命
  • 【AI知识管理系统】(一)AI知识库工具测评
  • 美颜SDK x AIGC:如何用滤镜API结合AI生成技术打造创意视觉特效?
  • CI/CD构建与注意事项
  • gazebo报错:[Err] [InsertModelWidget.cc:302] Missing model.config for model
  • 【最佳实践】Go 状态模式
  • 蓝桥杯学习-11栈
  • Gone v2 Tracer 组件-给微服务提供统一的traceID
  • 深入解析Java面向对象三大特征之多态、final、抽象类与接口
  • CMake学习笔记(二):变量设值,源文件/文件查找
  • 网络安全运维应急响应与溯源分析实战案例