使用版本
???"vue": "3.1.4",
? ? "vue-class-component": "^8.0.0-0-rc.1",
? ? "vue-router": "^4.0.0-0",
? ? "vuex": "^4.0.0-0",
? ? "vuex-module-decorators": "^1.0.1"
? ? ? ?上一篇文章中:Vue2增加动态缓存KeepAlive,列表、详情? 增加了动态缓存,同理迁移到vue3就不大好用了,针对这个版本,做了调整,贴代码:
1、修改路由增加<keep-alive>
这是个二级路由的Layout页面
注意:keep-alive不要写if语句,include如果是空字符串会判断为命中,生成缓存。
<template>
<router-view v-slot="{ Component }">
//动态生成缓存,和vue2写法不一样
<div v-if="keepRoute === 'ExamScorePersonList'">
<keep-alive :include="keepRoute">
<component :is="Component" />
</keep-alive>
</div>
<div v-else>
<component :is="Component" />
</div>
</router-view>
</template>
<script lang="ts">
import { Vue, Options } from 'vue-class-component'
@Options({
name: 'ExamLayout',
computed: {
keepRoute: function () {
return this.$store.state.aliveRoutes.keepAliveRoute
},
},
})
export default class ExamLayout extends Vue {}
</script>
2、增加store
?新建?aliveRoutes.ts
import {
VuexModule,
Module,
Mutation,
Action,
getModule,
} from 'vuex-module-decorators'
import store from '@/store'
@Module({ name: 'aliveRoutes', dynamic: true, store })
export default class AliveRoutes extends VuexModule {
public keepAliveRoute = ''
@Mutation
private UPDATE_KEEPALIVEROUTE(routeName: string) {
console.log('UPDATE_KEEPALIVEROUTE', routeName)
this.keepAliveRoute = routeName
}
@Action
public updateKeepAliveRoute(routeName: string) {
this.UPDATE_KEEPALIVEROUTE(routeName)
}
}
export const AliveRoutesIns = getModule(AliveRoutes)
3、动态路由使用及动态数据维护
修改列表文件,我这里是examScorePersonList.vue。
beforeRouteEnter(to: any, from: any, next: any) {
//每次进来,开启列表缓存
AliveRoutesIns.updateKeepAliveRoute('ExamScorePersonList')
next()
}
beforeRouteLeave(to: any, from: any, next: any) {
if (to.name === 'ExamScoreScore') { //跳转到详情,保持缓存
AliveRoutesIns.updateKeepAliveRoute('ExamScorePersonList')
} else { //跳转到其他页面,不再缓存
AliveRoutesIns.updateKeepAliveRoute('')
}
next()
}
?完成~~~2021.12.16
当然也可以把动态数据维护写到路由守卫中
?如果维护多个字段,维护数据可以生成数组呦~~,include时候用逗号,连接判断。
|