vue中页面跳转拦截器的实现方法

首先对index.js的router进行配置;

export default new Router({ 
 routes: [ 
  { 
   path: '/consultancy', 
   name: 'consultancy', 
   meta: { 
    requireAuth: true // 配置此条,进入页面前判断是否需要登陆 
   }, 
   component: selfcenter 
  } 
 ] 
})

定义完路由后,我们主要是利用vue-router提供的钩子函数beforeEach()对路由进行判断。

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限
    if (localStorage.getItem("userid")!=null ) { // 通过vuex state获取当前的userid是否存在
      next();
    } else {
      next({
        path: './',
        query: { redirect: to.fullPath } // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  }
  else {
    next();
  }
})

猜你喜欢

转载自www.cnblogs.com/Tohold/p/9101406.html