Vue 拦截路由

老子叫甜甜 提交于 2019-12-04 02:33:29

拦截器 

1.拦截路由 

// 拦截器// 路由拦截// to去哪个路由,from 从哪里来,next下一步router.beforeEach((to,from,next)=>{  // 如果是去login1  if (to.path == '/login1'){    //进行下一步    next();  } else{    //如果localStorage有值    if (localStorage.getItem('user_id')) {      next()      //否则回login1    }else{        next('/login1')    }  }})

最初的代码  我们进行优化 ,优化完

router.beforeEach((to, from, next) => {    if (to.path == '/login1' || localStorage.getItem('user_id')) {        next()    } else {        alert('请登录')        next('/login1')    }})优化完 看上去更精简 

 

2拦截请求 

axios.interceptors.request.use(function (hh) {  if (!localStorage.getItem('user_id')){    router.path({      name:'/login1'    })  } else{    hh.headers.user_id=localStorage.getItem('user_id')// 将localStorage.getItem('user_id') 发送到http的请求头里 
  }  return hh},function (error) {})

 

 

 

 

 

 

 

 

 

 

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!