需要達到的效果:
列表頁------->詳情頁/修改------>返回列表頁(緩存列表頁)
其它不緩存
//vuex/index.js new Vuex.store({ state: { catchPages: [] }, mutations: { add(state, item) { if (state.catchPages.indexOf(item) === -1) state.catchPages.push(item); }, remove(state, item) { let index = state.catchPages.indexOf(item); if(index >0) state.catchPages.splice(index, 1) } }, actions: { add(state, item) { state.commit('add', item) }, remove(state, item) { state.commit('remove', item) }, }, getters: { catchPages(content){ return content.catchPages; } } })
路由入口的寫法:
<!--app.vue--> <keep-alive :include="$store.getters.catchPages"> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
在路由鈎子 beforeRouteLeave 中把需要緩存的組件的name加入 vuex 中的 catchPages 數組中
beforeRouteLeave(to,from,next){ //do something next();
}