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
//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>
// 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 }
})

// 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>

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

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

onActivated讲解

你可能感兴趣的:(前端,vue.js,前端,javascript)