前提:有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>
到这里就实现了需求
PS:vue keep-alive include无效
检查版本
确定当前的vue版本的是2.1+
因为include和exclude是vue2.1.0新增的两个属性.
package.json
"vue": "^2.5.2",
检查name
注意,不是router.js中的name,而是单个vue组件中的name属性.
建议将router.js中的name和vue组件的name保持一致,不要混乱.
export default {
name: "index"
}
多层嵌套
网上的答案几乎都是检查vue组件的name属性,但还是有一个巨坑.
那就是多级嵌套<router-view></router-view>,但凡有超过两个以上的router-view且是父子级关系,请都加上keep-alive,只加一个不会生效.
// app.vue
<keep-alive include="app,index">
<router-view></router-view>
</keep-alive>
// other.vue
<keep-alive include="app,index">
<router-view></router-view>
</keep-alive>