在AppMain中添加keep-alive组件(路由暂时先全部缓存)和 transition组件

image.png

切换到其他路由页再回来内容还在

5-1创建AppMain组件

src/layout/components/AppMain.vue
vue router路由缓存迁移指南

  1. <template>
  2. <div class="app-main">
  3. <!-- vue3 路由缓存 https://next.router.vuejs.org/guide/migration/index.html#router-view-keep-alive-and-transition -->
  4. <router-view v-slot={Component}>
  5. <transition name="fade-transform" mode="out-in">
  6. <keep-alive>
  7. <component :is="Component" :key="key" />
  8. </keep-alive>
  9. </transition>
  10. </router-view>
  11. </div>
  12. </template>
  13. <script lang="ts">
  14. import { computed, defineComponent } from 'vue'
  15. import { useRoute } from 'vue-router'
  16. export default defineComponent({
  17. name: 'AppMain',
  18. setup() {
  19. const route = useRoute()
  20. const key = computed(() => route.path)
  21. return {
  22. key
  23. }
  24. }
  25. })
  26. </script>
  27. <style lang="scss" scoped>
  28. .app-main {
  29. /* navbar 50px */
  30. min-height: calc(100vh - 50px);
  31. }
  32. .fade-transform-enter-active,
  33. .fade-transform-leave-active {
  34. transition: all .5s;
  35. }
  36. .fade-transform-enter-from {
  37. opacity: 0;
  38. transform: translateX(-30px);
  39. }
  40. .fade-transform-leave-to {
  41. opacity: 0;
  42. transform: translateX(30px);
  43. }
  44. </style>

5-2 layout中导入AppMain组件

src/layout/index.vue
image.png

  1. <template>
  2. <div class="app-wrapper">
  3. <div class="sidebar-container">
  4. <Sidebar />
  5. </div>
  6. <div class="main-container">
  7. <div class="header">
  8. <div class="navbar">navbar</div>
  9. <div class="tags-view">tagsview</div>
  10. </div>
  11. <!-- AppMain router-view -->
  12. <app-main />
  13. </div>
  14. </div>
  15. </template>
  16. <script lang="ts">
  17. import { defineComponent } from 'vue'
  18. import Sidebar from './components/Sidebar'
  19. import AppMain from './components/AppMain.vue'
  20. export default defineComponent({
  21. components: {
  22. Sidebar,
  23. AppMain
  24. }
  25. })
  26. </script>
  27. <style lang="scss" scoped>
  28. .app-wrapper {
  29. display: flex;
  30. width: 100%;
  31. height: 100%;
  32. .main-container {
  33. flex: 1;
  34. display: flex;
  35. flex-direction: column;
  36. .header {
  37. background: cyan;
  38. .navbar {
  39. height: 50px;
  40. background: #1890ff;
  41. }
  42. .tags-view {
  43. height: 34px;
  44. background: #12efff;
  45. }
  46. }
  47. .app-main {
  48. /* 50= navbar 50 如果有tagsview + 34 */
  49. min-height: calc(100vh - 84px);
  50. }
  51. }
  52. }
  53. </style>

5-3 缓存测试

input输入内容切换路由还在

image.png

本节参考源码

https://gitee.com/brolly/vue3-element-admin/commit/34bb87edbc56ca3760d7730ca04a3c20cd73d251