vue拦截器

一 路由拦截器

项目中,用户不登录只能去登录页面,不可以访问别的页面,这种情况的话,可以用路由拦截器

1. 先说下区分下route与router
  • route:相当于当前正在跳转的路由对象。可以从里面获取name,path,params,query等。
    如取路由带来的参数:this.$route.params
  • router:VueRouter的实例,相当于一个全局的路由器对象,里面含有很多属性和子对象,例如history对象。。。经常用的跳转链接就可以用this.$router.push,和router-link跳转一样
//带参数路由跳转
this.$router.push({path:'/home',params:{id:123}})
//取参数
this.$route.params.id //123
  • 两个的打印如下:


    2e0d46f2fc13f4c5b7c7e720718b741.png

2. 言归正传说路由拦截

//路由拦截器
//to为向后走的路由对象,包括路由的完整信息
//from为从哪跳来的路由对象
//next()控制路由向下走,重新定义路由跳转的路由next(‘路由路径)
/** 验证用户是否登录 **/
router.beforeEach((to,from,next) => {
    if(to.matched.some( m => m.meta.auth)) {
        // console.log("先判断是否登录");
        if(to.name=='Login'){
            next();
        }else{
          if(localStorage.getItem('token')){

          //访问服务器缓存数据,判断当前token是否失效
            Vue.http.get("http:xxxx/Login/UserIsLogin?token="+localStorage.getItem('token')+"&url="+to.name,{withCredentials: true}).then(response => response.json()).then(num => {
                    // console.log('是否登录',num);
                    if(num.code==1001){
                        next();
                    }else{
                        alert('您的token已超时,请重新登录');
                        next('/Login');
                    }
            })
          }else{
            next('/Login');
          }

        }
   } else {
        console.log("请先登录");
        next()
    }
})

//或者简洁的可以:
router.beforeEach((to,from,next)=>{
    if(localStorage.getItem('token')||to.name=='login'){
          next()
    }else{
          //如果没有token值,则跳到登录页面
          next({path:'/login'})
    }
   next()
})

二 请求拦截

统一处理错误及配置请求信息

  1. 安装 axios , 命令: npm install axios --save-dev
  2. 在根目录的config目录下新建文件 axios.js ,内容如下:
    import axios from 'axios'
    // 配置默认的host,假如你的API host是:http://api.htmlx.club
    axios.defaults.baseURL = 'http://api.htmlx.club'
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config
}, function (error) {
  // 对请求错误做些什么
return Promise.reject(error)
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error)
});

请求拦截 根据自己的需求加对应的代码

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容