vue 两个以上路由如何做到前进刷新,后退不刷新

两个以上路由,a->b->c ... 前进时每次进入页面都要请求数据,...c->b->a返回时不再请求数据,读取缓存内容,类似移动端APP的效果。

查阅资料发现目前基本都是靠keep-alive和beforeRouteLeave结合使用的。
<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) {
         // 设置下一个路由的 meta
        to.meta.keepAlive = true;  // 让 A 缓存,即不刷新
        next();
    }
};

以上代码都出自简书上下面这个大佬的文章

作者:RoamIn
链接:http://www.jianshu.com/p/0b0222954483
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

测试后发现对于a->b b->a 这种,两个路由之间的前进后退很有效果,但是对于超过两个的路由,我就做不出来了,我也向简书的这个作者提问了,不过暂未收到回复。

可能是我还没有领悟上面这种方法的要领,所以在此提问,各位大佬,对于这种多路由前进后退缓存问题如何解决。

阅读 6.4k
3 个回答

维护一个路由名列表 routerList
router.beforeEach 的时候判断 to 的 name 是不是在 routerList 的最后一个
如果是就是后退,把 routerList 最后一个剔除,设置 to.meta.keepAlive 为 false
如果不是则是前进,把 to.name push 进 routerList,设置 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()
})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题