前提:有A,B,C,D四个页面,A是按钮页(点击按钮进入B页面),B是订单列表页,C是订单详情页,D是费用详情页
需求:顺序是A->B->C->D,每次都刷新页面,D->C->B时走缓存,但是每次从A到B都要刷新B页面,从B到C需要刷新C页面,从C到D要刷新D页面
在vue官方文档2.1以上有include 和 exclude 属性允许组件有条件地缓存。在这里主要用include结合vuex来实现(四个页面组件都有自己的name才会生效,这里name就叫A,B,C,D)
从D->C,从C->B,从B->A 可以写一个公共的头部返回组件,统一使用 this.$router.go(-1)返回前一页
App.vue
<template> <div class="app"> <keep-alive :include="keepAlive" > <router-view/> </keep-alive> </div> </template> <script type=\'text/javascript\'> export default { data () { return {} }, computed: { keepAlive () { return this.$store.getters.keepAlive } } } </script>
store.js
import Vue from \'vue\' import Vuex from \'vuex\' Vue.use(Vuex) export default new Vuex.Store({ state: { keepAlive: [] }, mutations: { SET_KEEP_ALIVE: (state, keepAlive) => { state.keepAlive = keepAlive } }, getters: { keepAlive: state => state.keepAlive } })
每次进入B页面时先初始化 keepAlive(设置要走缓存的页面)
A.vue
<script> export default { name: \'A\', methods: { buttonClick () { this.$store.commit(\'SET_KEEP_ALIVE\', [\'B\', \'C\', \'D\'])
this.$router.push(\'/B\')
}
}
}
</script>
B.vue 该页面用来设置缓存和清除缓存
<script> export default { name: \'B\', beforeRouteEnter (to, from, next) { next(vm => { if (from.path.indexOf(\'C\') > -1) { vm.$store.commit(\'SET_KEEP_ALIVE\', [\'B\']) } }) }, beforeRouteLeave (to, from, next) { if (to.path.indexOf(\'C\') > -1) { this.$store.commit(\'SET_KEEP_ALIVE\', [\'B\', \'C\']) } else if (to.path.indexOf(\'A\') > -1) {
this.$store.commit(\'SET_KEEP_ALIVE\', [])
} next() } } </script>
到这里就实现了需求