fix:修复keep-alive失效问题,并添加keep-alive测试页面

This commit is contained in:
zhangchuanlong 2022-03-04 16:44:33 +08:00
parent 402c7db7ba
commit 8bcbcac531
5 changed files with 51 additions and 18 deletions

View File

@ -3,16 +3,11 @@ import AppProvider from '@/components/AppProvider/index.vue'
</script>
<template>
<router-view>
<template #default="{ Component, route }">
<app-provider>
<keep-alive v-if="route.meta && route.meta.keepAlive">
<component :is="Component" :key="route.fullPath" />
</keep-alive>
<component :is="Component" v-else :key="route.fullPath" />
</app-provider>
</template>
<router-view v-slot="{ Component }">
<component :is="Component" />
</router-view>
</app-provider>
</template>
<style lang="scss">

View File

@ -9,14 +9,13 @@ const appStore = useAppStore()
<template>
<n-config-provider :theme-overrides="appStore.themeOverrides">
<n-global-style />
<n-loading-bar-provider>
<loading-bar />
<n-dialog-provider>
<dialog-content />
<n-message-provider>
<message-content />
<slot name="default"></slot>
<slot></slot>
</n-message-provider>
</n-dialog-provider>
</n-loading-bar-provider>

View File

@ -1,9 +1,19 @@
<template>
<router-view>
<template #default="{ Component, route }">
<router-view v-slot="{ Component, route }">
<transition name="fade-slide" mode="out-in" appear>
<component :is="Component" :key="route.fullPath"></component>
<keep-alive :include="keepAliveRouteNames">
<component :is="Component" :key="route.path" />
</keep-alive>
</transition>
</template>
</router-view>
</template>
<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const allRoutes = router.getRoutes()
const keepAliveRouteNames = computed(() => {
return allRoutes.filter((route) => route.meta?.keepAlive).map((route) => route.name)
})
</script>

View File

@ -104,6 +104,15 @@ export const basicRoutes = [
title: '测试Dialog',
},
},
{
name: 'TEST-KEEP-ALIVE',
path: 'keep-alive',
component: () => import('@/views/test-page/TestKeepAlive.vue'),
meta: {
title: '测试Keep-Alive',
keepAlive: true,
},
},
],
},

View File

@ -0,0 +1,20 @@
<!--使用keep-alive须设置name注意请与对应的路由的name保持一致方便统一处理-->
<script setup name="TEST-KEEP-ALIVE">
import { onMounted, onActivated, onDeactivated } from 'vue'
onMounted(() => {
$message.success('触发onMounted')
})
onActivated(() => {
$message.success('触发onActivated')
})
onDeactivated(() => {
$message.success('触发onDeactivated')
})
</script>
<template>
<n-gradient-text gradient="linear-gradient(90deg, red 0%, green 50%, blue 100%)"> 注意查看提示语 </n-gradient-text>
</template>