vue中怎样实现 路由拦截器

2019-10-24  本文已影响0人  致青春永恒

当用户没有登录的时候,跳转到登录页面,已经登录的时候,不能跳转到登录页,除非后台token失效(复制登录中的页面链接到新页面打开跳转到登录页)

1,复制登录中的页面链接到新页面打开跳转到登录页

//http response 拦截器

axios.interceptors.response.use(

  response => {

    if (sessionStorage.getItem('tokey') == null) {

        // console.log("token过期");

        router.push({path: "/pages/login"})

    }

    return response;

  },

  error => {

    return Promise.reject(error)

  }

)

2,现在 我们需要实现这样 一个功能,登录拦截

其实就是 路由拦截,首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录。如果用户已经登录,则顺利进入路由, 否则就进入登录页面。在路由管理页面添加meta字段

router/index.js文件,例如,在用户直接跳转/manage 路径下的时候,实现路由拦截

{

          path:'/manage',

          name:'manage',

          component:manage,

          meta:{requireAuth:true}

  },

我们需要在main.js 中加上

router.beforeEach((to, from, next) => {

  console.log(to);

  console.log(from);

  if (to.meta.requireAuth) { // 判断该路由是否需要登录权限

    if(localStorage.getItem('access_token')){ //判断本地是否存在access_token

      next();

    }else {

    if(to.path === '/login'){

        next();

      }else {

        next({

          path:'/login'

        })

      }

    }

  }

  else {

    next();

  }

  /*如果本地 存在 token 则 不允许直接跳转到 登录页面*/

  if(to.fullPath == "/login"){

    if(localStorage.getItem('access_token')){

      next({

        path:from.fullPath

      });

    }else {

      next();

    }

  }

});

参数说明:

     * to: Route: 即将要进入的目标 路由对象 

     * from: Route: 当前导航正要离开的路由 

     * next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。 

上一篇下一篇

猜你喜欢

热点阅读