• vue3 keepalive跳转页面保存页面状态


    描述

    实现页面 A-> B , B->A(A保存之前页面状态,不刷新页面

    // router/index.ts
    
    import { createRouter, createWebHistory } from 'vue-router'
    import HomeView from '../views/HomeView.vue'
    
    const router = createRouter({
      history: createWebHistory(import.meta.env.BASE_URL),
      routes: [
        {
          path: '/',
          name: 'home',
          component: HomeView,
          // 默认选择第一个子路由
          redirect:'/index',
          children:[
            {
              path: 'index',
              name: 'FirstViews',
              component: () => import('@/components/FirstViews.vue'),
              // meta: { keepAlive: false,} // 组件需要缓存
            },
            {
              path: 'modelShowing',
              name: 'MainTag',
              component: () => import('@/components/MainTag.vue'),
              // meta: { keepAlive: true,} // 组件需要缓存 (可有可无,我这里没有影响)
            },
            {
              path: 'projectShowing',
              name: 'MainTagProject',
              component: () => import('@/components/MainTagProject.vue'),
              // meta: { keepAlive: false,} // 组件需要缓存
            }
          ]
        },
        {
          path: '/about',
          name: 'about',
          component: () => import('../views/AboutView.vue'),
          // meta: { keepAlive: false,} // 组件需要缓存
        },
        {
          path: '/models3DShow',
          name: 'models3DShow',
          component: () => import('@/components/models3DShow.vue'),
          // meta: { keepAlive: false,} // 组件需要缓存
        }
      ],
      scrollBehavior(to,from,savedPosition) {
        return {top : 0}
      }
    })
    
    export default router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    //App.vue
    
    <script setup lang="ts">
    import {RouterLink, RouterView, useRoute, useRouter} from 'vue-router'
    import HelloWorld from './components/HelloWorld.vue'
    import {defineComponent, onMounted, watch} from 'vue'
    import { ElConfigProvider } from 'element-plus'
    import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
    import MainTag from "@/components/MainTag.vue";
    import {usekeepaliveStateStore} from "@/stores/keepaliveState";
    import {ref} from "vue";
    const  locale = ref(zhCn)
    const tag = ref('MainTag')
    const keepaliveState = usekeepaliveStateStore()
    let includeList = ref([])
    let router = useRouter()
    let route = useRoute()
    
    onMounted(()=>{
    })
    
    watch(()=> route.name,(newValue, oldValue)=>{
      //从组织架构进入文章列表,默认文章列表是缓存的
      console.log(newValue, oldValue)
      console.log(keepaliveState.useKeepaliveState)
    
    })
    </script>
    
    <template>
      <el-config-provider :locale="locale">
    <!--    <RouterView></RouterView>-->
        <router-view v-slot="{ Component, route }">
                <keep-alive :include="keepaliveState.useKeepaliveState">
                  <component :is="Component" :key="route.path"/>
                </keep-alive>
        </router-view>
      </el-config-provider>
    </template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    // store/keepaliveState.ts
    
    import { defineStore } from "pinia";
    import {ref} from "vue";
    
    export const usekeepaliveStateStore = defineStore('keepaliveState',() =>{
        const useKeepaliveState = ref(['MainTag','home']) // 重点 要有 home
        function increment(data){
            useKeepaliveState.value = data
        }
        function deletes(pathName){
            useKeepaliveState.value.indexOf(pathName) > -1 && useKeepaliveState.value.splice(useKeepaliveState.value.indexOf(pathName), 1)
        }
        function adds(pathName) {
            useKeepaliveState.value.indexOf(pathName) == -1 && useKeepaliveState.value.push(pathName)
        }
        return { useKeepaliveState, increment,deletes,adds }
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    // HomeView.vue
    <script lang="ts" setup>
    import { defineComponent } from 'vue'
    import HeaderView from "@/views/HeaderView.vue";
    import CarouselMenu from "@/components/home/CarouselMenu.Vue";
    import SlotViews from "@/components/SlotViews.vue";
    import FooterMenu from "@/components/home/FooterMenu.vue";
    
    import MainTag from "@/components/MainTag.vue";
    import {useRoute, useRouter} from "vue-router";
    
    const route = useRoute();
    const router = useRouter();
    defineOptions({
      name: "home",
      inheritAttrs: true
    })
    const modules = []
    const carouselImgList = [
        "/images/example/1.jpg",
        "/images/example/2.jpg",
        "/images/example/3.jpg",
        "/images/example/4.jpg",
        "/images/example/5.jpg"
    ]
    // 植物模型
    const plantsModels = [
      {
        id: 1,
        name: "白及",
        imgSrc: "/img/plants1.png"
      },
    ]
    
    // 生长动画
    const grow = []
    
    // 药材模型
    const drug = []
    
    // 畜牧解剖
    const animal = []
    const getMenu=(itemNum) => {
      console.log(`itemNum : ${itemNum}`)
      switch (itemNum) {
        case 1:
          router.push({path:'/index'})
          break
        case 2:
          router.push({path:'/modelShowing'})
          break
        case 3:
          router.push({path:'/projectShowing'})
          break
        default:
          router.push({path:'/index'})
      }
    }
    </script>
    
    <template>
      <div class="common-layout">
        <el-container>
          <el-header class="header">
            <HeaderView @get-menu="getMenu"/>
          </el-header>
          <router-view v-slot="{ Component, route }">
            <keep-alive >
              <component :is="Component" :key="route.path"/>
            </keep-alive>
          </router-view>
          <el-footer>
            <FooterMenu/>
          </el-footer>
        </el-container>
      </div>
    </template>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77

    App页面和父组件页面都需要 keepalive 配置,且父组件和子组件名字都需要添加到keepalive inclued内

    注意:组件注册名称 name要和router内的name一致。

    查看 onActivated ,onDeactivated 判断 keepalive是否生效

    onActivated讲解

  • 相关阅读:
    什么是 RPA?
    航迹管理软件——SPx Track Manager
    MyBatis开荒
    python学习笔记5-堆
    顾樵 量子力学I 导读(1)
    【智能优化算法-飞蛾扑火优化算法】基于水循环混合飞蛾扑火优化算法求解约束的工程优化问题附matlab代码WCMFO
    Spring中的Cache缓存机制
    小程序云开发汇总
    leetcode 45
    康耐视深度学习ViDi-Plugins菜单介绍
  • 原文地址:https://blog.csdn.net/w710537643/article/details/133646316