鍍金池/ 問答/HTML/ vue 兩個以上路由如何做到前進刷新,后退不刷新

vue 兩個以上路由如何做到前進刷新,后退不刷新

兩個以上路由,a->b->c ... 前進時每次進入頁面都要請求數(shù)據(jù),...c->b->a返回時不再請求數(shù)據(jù),讀取緩存內(nèi)容,類似移動端APP的效果。

查閱資料發(fā)現(xiàn)目前基本都是靠keep-alive和beforeRouteLeave結(jié)合使用的。
<keep-alive>
    <router-view v-if="$route.meta.keepAlive">
        <!-- 這里是會被緩存的視圖組件,比如 Home! -->
    </router-view>
</keep-alive>

<router-view v-if="!$route.meta.keepAlive">
    <!-- 這里是不被緩存的視圖組件,比如 Edit! -->
</router-view>
// routes 配置
export default [
  {
    path: '/',
    name: 'home',
    component: Home,
    meta: {
      keepAlive: true // 需要被緩存
    }
  }, {
    path: '/:id',
    name: 'edit',
    component: Edit,
    meta: {
      keepAlive: false // 不需要被緩存
    }
  }
]
export default {
    data() {
        return {};
    },
    methods: {},
    beforeRouteLeave(to, from, next) {
         // 設(shè)置下一個路由的 meta
        to.meta.keepAlive = true;  // 讓 A 緩存,即不刷新
        next();
    }
};

以上代碼都出自簡書上下面這個大佬的文章

作者:RoamIn
鏈接:http://www.jianshu.com/p/0b0222954483
來源:簡書
著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。

測試后發(fā)現(xiàn)對于a->b b->a 這種,兩個路由之間的前進后退很有效果,但是對于超過兩個的路由,我就做不出來了,我也向簡書的這個作者提問了,不過暫未收到回復(fù)。

可能是我還沒有領(lǐng)悟上面這種方法的要領(lǐng),所以在此提問,各位大佬,對于這種多路由前進后退緩存問題如何解決。

回答
編輯回答
若相惜
2018年5月5日 11:10
編輯回答
吢涼

維護一個路由名列表 routerList
router.beforeEach 的時候判斷 to 的 name 是不是在 routerList 的最后一個
如果是就是后退,把 routerList 最后一個剔除,設(shè)置 to.meta.keepAlive 為 false
如果不是則是前進,把 to.name push 進 routerList,設(shè)置 to.meta.keepAlive 為 true
不需要在頁面組件里寫beforeRouteLeave了

var routerList = []
router.beforeEach((to, from, next) => {
  if (routerList.length && routerList.indexOf(to.name) === routerList.length - 1) { // 后退
    routerList.splice(routerList.length - 1,1)
    to.meta.keepAlive = true
  } else { // 前進
    routerList.push(to.name)
    to.meta.keepAlive = false
  }
  next()
})
2017年9月14日 22:11