方法二:使用 include + beforeRouteLeave + vuex 與方法一相似,不同的地方在于,將需要緩存的組件保存到全局變量,可以在路由的鉤子函數(shù)里靈活的控制哪些組件需要緩存,那些不需要緩存;跟方法一相比,不需要每次再重新初始化數(shù)據(jù),但是需要在vuex中保存數(shù)據(jù);
1、在創(chuàng)建router實例的時候加上scrollBehavior方法
export default new Router({
routes,
scrollBehavior (to, from, savedPosition) {
if (savedPosition) {
return savedPosition
} else {
return {
x: 0,
y: 0
}
}
}
})
2、將需要緩存的組件加在include屬性里
<keep-alive :include="catch_components">
<router-view></router-view>
</keep-alive>
3、在store里加入需要緩存的的組件的變量名,和相應(yīng)的方法;
export default new Vuex.Store({
state: {
catch_components: []
},
mutations:{
GET_CATCHE_COMPONENTS (state, data) {
state.catch_components = data
}
}
})
4、在beforeRouteLeave鉤子函數(shù)里控制需要緩存的組件
beforeRouteLeave (to, from, next) { //要在離開該組件的時候控制需要緩存的組件,否則將出現(xiàn)第一次不緩存的情況
this.busy = true
if (to.path === '/goods_detail') { // 去往詳情頁的時候需要緩存組件,其他情況下不需要緩存
this.$store.commit('GET_CATCHE_COMPONENTS', ['home']) //注意,'home'將匹配首先檢查組件自身的 name 選項(非router.js里的),如果 name 選項不可用,則匹配它的局部注冊名稱 (父組件 components 選項的鍵值)。匿名組件不能被匹配。
} else {
this.$store.commit('GET_CATCHE_COMPONENTS', [])
}
next()}