码迷,mamicode.com
首页 > Web开发 > 详细

vue拦截器Vue.http.interceptors.push

时间:2017-04-22 12:54:05      阅读:828      评论:0      收藏:0      [点我收藏+]

标签:tar   method   actions   from   returns   逻辑   alt   set   down   

刚开始学vue,github上down了一个开源项目,看源代码的时候看到了这个地方:

技术分享

/**
 * @export
 * @param {any} request
 * @param {any} next
 * @returns
   */
import store from ‘./vuex/store‘
// 全局错误处理,全局loading
import { setLoading, setTip } from ‘./vuex/actions/doc_actions‘
export default function (request, next) {
  if (request.tip !== false) {
    setLoading(store, true)
  }
  next((res) => {
    setLoading(store, false)
    let data = JSON.parse(res.data)
    if (res.status === 0) {
      setTip(store, {
        text: ‘网络不给力,请稍后再试‘
      })
    }
    if (!data.success) {
      setTip(store, {
        text: data.error_msg
      })
    }
  })
}

 

这是一个全局的拦截器。于是搜索vue拦截器的用法,下面这一篇写的不错:

http://www.cnblogs.com/dupd/p/6048018.html

在vue项目使用vue-resource的过程中,临时增加了一个需求,需要在任何一个页面任何一次http请求,增加对token过期的判断,如果token已过期,需要跳转至登录页面。如果要在每个页面中的http请求操作中添加一次判断,那么会是一个非常大的修改工作量。那么vue-resource是否存在一个对于任何一次请求响应捕获的的公共回调函数呢?答案是有的!

vue-resource的interceptors拦截器的作用正是解决此需求的妙方。在每次http的请求响应之后,如果设置了拦截器如下,会优先执行拦截器函数,获取响应体,然后才会决定是否把response返回给
then进行接收。那么我们可以在这个拦截器里边添加对响应状态码的判断,来决定是跳转到登录页面还是留在当前页面继续获取数据。拦截器详细介绍》》
下边代码添加在main.js中
Vue.http.interceptors.push((request, next) => {
 console.log(this)//此处this为请求所在页面的Vue实例
  // modify request
  request.method = ‘POST‘;//在请求之前可以进行一些预处理和配置

  // continue to next interceptor

  next((response) => {//在响应之后传给then之前对response进行修改和逻辑判断。对于token时候已过期的判断,就添加在此处,页面中任何一次http请求都会先调用此处方法

      response.body = ‘...‘;
    return response;

  });

});

 

vue拦截器Vue.http.interceptors.push

标签:tar   method   actions   from   returns   逻辑   alt   set   down   

原文地址:http://www.cnblogs.com/guazi/p/6747219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!