This article records the problems I encountered when using vue-router when developing a vue project.

routes

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

navigation guard

 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()
  }
})

The above configuration will check whether there is permission control before entering the route. If you need to log in, the login monitoring event will be triggered and the login window will pop up. If it is a route from another project to the vue project, the login window cannot pop up normally, because the single-page application is loaded for the first time, and $bus has not been registered.

Handling page load progress bar

 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}
    }
  },
})

来了老弟
508 声望31 粉丝

纸上得来终觉浅,绝知此事要躬行