vue3 动态修改 keepAlive
需求场景:
跳转逻辑
A
跳转B
,B
页面 表单填写过程中 跳转 选择地址等额选项时,我们需要将B
页面 进行 keepAlive 缓存,达到 返回时不重新渲染
但是我们需要考虑 从
A
页面到B
页面 需要全部重新加载,此类场景 我们需要 动态的去控制 keepAlive
流程图 A
页面 > B
页面(表单页面) < 互相跳转 > C
页面(额外选项 选择地址类似)
App.vue
<!-- vue3.0配置 -->
<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>
复制代码
import { useRoute } from 'vue-router';
export default defineComponent({
name: 'App',
setup(props) {
const route = useRoute();
return { route }
}
})
复制代码
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
}
},
复制代码
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') {
// 不是去 c 页面,不缓存
changeRouterKeepAlive(from.name as string, false);
} else {
changeRouterKeepAlive(from.name as string, true);
}
});
return { };
}
})
复制代码