关于vue-router:vuerouter相关配置

本文记录一下我在开发vue我的项目时,应用vue-router遇到过得问题。

routes

const routes = [
  {
    path: '/cardLesson',
    name: 'cardLesson',
    component: () => import( '../views/myCard/cardLesson'),
    meta: {
      auth: false,
      needPhone: false,
      keepAlive: false
    }
  },
  ...
]

导航守卫

router.beforeEach((to, from, next) => {
  if (to.meta && to.meta.auth) {
    if (!Vue.prototype.$checkLogin()) {
      return Vue.prototype.$bus.$emit('auth-login')
    }
    if (to.meta.needPhone && !Vue.prototype.$checkPhone()) {
      return Vue.prototype.$bus.$emit('auth-phone')
    }
    return next()
  } else {
    next()
  }
})

以上的配置,在进入路由前会先检测有没有权限管制,如果须要登录则会触发登录监听事件,弹出登录窗口。如果是从其余我的项目跳转到vue我的项目的路由,却无奈失常弹出登录窗口,因为单页面利用第一次加载,$bus还没有注册。

解决页面加载进度条

router.beforeEach((to, from, next) => {
  NProgress.start();
  to.meta.keepAlive = !(to.meta && to.meta.skipCache);
  next()
});

router.afterEach(() => {
  NProgress.done()
});

scrollBehavior

const router = new VueRouter({
  routes,
  scrollBehavior(to,from,saveTop){
    if(saveTop){
      return saveTop;
    }else{
      return {x:0,y:0}
    }
  },
})

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理