在AppMain中添加keep-alive组件(路由暂时先全部缓存)和 transition组件
5-1创建AppMain组件
src/layout/components/AppMain.vue
vue router路由缓存迁移指南
<template>
<div class="app-main">
<!-- vue3 路由缓存 https://next.router.vuejs.org/guide/migration/index.html#router-view-keep-alive-and-transition -->
<router-view v-slot={Component}>
<transition name="fade-transform" mode="out-in">
<keep-alive>
<component :is="Component" :key="key" />
</keep-alive>
</transition>
</router-view>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue'
import { useRoute } from 'vue-router'
export default defineComponent({
name: 'AppMain',
setup() {
const route = useRoute()
const key = computed(() => route.path)
return {
key
}
}
})
</script>
<style lang="scss" scoped>
.app-main {
/* navbar 50px */
min-height: calc(100vh - 50px);
}
.fade-transform-enter-active,
.fade-transform-leave-active {
transition: all .5s;
}
.fade-transform-enter-from {
opacity: 0;
transform: translateX(-30px);
}
.fade-transform-leave-to {
opacity: 0;
transform: translateX(30px);
}
</style>
5-2 layout中导入AppMain组件
src/layout/index.vue
<template>
<div class="app-wrapper">
<div class="sidebar-container">
<Sidebar />
</div>
<div class="main-container">
<div class="header">
<div class="navbar">navbar</div>
<div class="tags-view">tagsview</div>
</div>
<!-- AppMain router-view -->
<app-main />
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import Sidebar from './components/Sidebar'
import AppMain from './components/AppMain.vue'
export default defineComponent({
components: {
Sidebar,
AppMain
}
})
</script>
<style lang="scss" scoped>
.app-wrapper {
display: flex;
width: 100%;
height: 100%;
.main-container {
flex: 1;
display: flex;
flex-direction: column;
.header {
background: cyan;
.navbar {
height: 50px;
background: #1890ff;
}
.tags-view {
height: 34px;
background: #12efff;
}
}
.app-main {
/* 50= navbar 50 如果有tagsview + 34 */
min-height: calc(100vh - 84px);
}
}
}
</style>
5-3 缓存测试
input输入内容切换路由还在
本节参考源码
https://gitee.com/brolly/vue3-element-admin/commit/34bb87edbc56ca3760d7730ca04a3c20cd73d251