Requirement scenarios:
Jump logic When page A jumps to page B and page B selects the address equal option in the form filling process, page B needs to be keepAlive cache and will not be re-rendered upon return
However, we need to consider the need to reload from page A to page B, and we need to control keepAlive dynamically in such scenarios
Flow chart PAGE A > PAGE B (form page) < Cross-jump > page C (additional options select similar address)
App.vue
<! -- Vue3.0 configuration -->
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" :key="route.name" v-if="route.meta.keepAlive" />
</keep-alive>
<component :is="Component" :key="route.name" v-if=! "" route.meta.keepAlive" />
</router-view>
Copy the code
import { useRoute } from 'vue-router';
export default defineComponent({
name: 'App'.setup(props) {
const route = useRoute();
return { route }
}
})
Copy the code
router.ts
// ...
{
path: 'path/BComponent'.name: 'BComponent'.component: BComponent,
meta: {
title: 'Page B'.keepAlive: true}}, {path: 'path/CComponent'.name: 'CComponent'.component: CComponent,
meta: {
title: 'Page C'.keepAlive: false}},Copy the code
B.vue
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
export default defineComponent({
name: 'B'.setup(props) {
const route = useRoute();
const router = useRouter();
const changeRouterKeepAlive = (name: string, keepAlive: boolean) = > {
router.options.routes.map((item: any) = > {
if(item.name === name) { item.meta.keepAlive = keepAlive; }}); }; onBeforeRouteLeave((to, from) = > {
if(to.name ! = ='c') {
// Do not go to c page, do not cache
changeRouterKeepAlive(from.name as string.false);
} else {
changeRouterKeepAlive(from.name as string.true); }});return{}; }})Copy the code