场景:
首页( A )——>添加页( B ): 不需要缓存B,清空表单数据
添加页( B )——>添加详情页( C ): 需要缓存B
1.App.vue
<keep-alive :include="kpAlive">
<router-view></router-view>
</keep-alive>
computed: {
kpAlive() {
return this.$store.state.cache.kpAliveRouter;
},
},
2.store/cache.js
const state = {
kpAliveRouter: []
}
const mutations = {
SET_KEEP_ALIVE: (state, data) => {
state.kpAliveRouter = data
}
}
export default {
namespaced: true,
state,
mutations
}
3.B.vue
const outAliveList = ["C"];
const currentName = "B"; //注意: 这里是组件名字,不是路由名字
methods: {
...mapMutations("cache", ["SET_KEEP_ALIVE"]),
}
// 页面缓存
beforeRouteEnter(to, from, next) {
next((vm) => {
vm.SET_KEEP_ALIVE([currentName]);
});
},
beforeRouteLeave(to, from, next) {
if (outAliveList.includes(to.name)) {
this.SET_KEEP_ALIVE([currentName]);
} else {
this.SET_KEEP_ALIVE([]);
}
next();
},
这里以vue-page-stack做介绍
main.js
import VuePageStack from 'vue-page-stack';
// vue-router is necessary
Vue.use(VuePageStack, { router });
App.vue
<template>
<div id="app">
<transition mode="out-in" :name="transitionName">
<vue-page-stack>
<router-view class="pages"></router-view>
</vue-page-stack>
</transition>
</div>
</template>
<script>
export default {
name: "app",
components: {},
mixins: [],
computed: {},
data() {
return {
transitionName: "",
};
},
watch: {
$route(to, from) {
if (to.params["stack-key-dir"] === "forward") {
this.transitionName = "fade-left";
} else {
this.transitionName = "fade-right";
}
console.log("this.transitionName", this.transitionName);
},
},
created() {},
mounted() {},
beforeDestroy() {},
destroyed() {},
methods: {},
};
</script>
<style>
</style>
<style lang="scss" scoped>
.fade-left-enter-active,
.fade-right-enter-active {
transition: all 0.3s ease;
}
.fade-left-leave-active,
.fade-right-leave-active {
// transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
transition: all 0.3s ease;
}
.fade-left-enter {
transform: translateX(100%);
}
.fade-right-enter {
transform: translateX(-100%);
}
</style>