Bootstrap

Vue进阶(幺伍伍):vue-resource 拦截器 interceptors 使用

一、前言

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

中拦截器的作用正是解决此需求的妙方。在每次请求响应之后,如果设置了拦截器,会优先执行拦截器函数,获取响应体,然后才会决定是否把返回给进行接收。那么我们可以在这个拦截器里边添加对响应状态码的判断,来决定是跳转到登录页面还是留在当前页面继续获取数据。

二、安装与引用

NPM:

/*引入Vue框架*/
import Vue from 'vue'
/*引入资源请求插件*/
import VueResource from 'vue-resource'

/*使用VueResource插件*/
Vue.use(VueResource)

下边代码添加在中

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;

  });
});

三、拦截器实例

3.1 为请求添加 loading 效果

通过,可以为所有的请求处理加一个:请求发送前显示,接收响应后隐藏。

具体步骤如下:

//1、添加一个loading组件


//2、将loading组件作为另外一个Vue实例的子组件
var help = new Vue({
    el: '#help',
    data: {
        showLoading: false
    },
    components: {
        'loading': {
            template: '#loading-template',
        }
    }
})

//3、将该Vue实例挂载到某个HTML元素
//4、添加inteceptor Vue.http.interceptors.push((request, next) => { loading.show = true; next((response) => { loading.show = false; return response; }); });

但是,当用户在画面上停留时间太久时,视图数据可能已经不是最新的了,这时如果用户删除或修改某一条数据,如果这条数据已经被其他用户删除了,服务器会反馈一个的错误,但由于和请求没有处理,所以用户是不知道他的操作是成功还是失败了。这个问题,同样也可以通过解决。

3.2 为请求添加共同的错误处理方法

//1、继续沿用上面的loading组件,在#help元素下加一个对话框

Server Error

Oops,server has got some errors, error code: {{errorCode}}.

//2、给help实例的data选项添加两个属性 var help = new Vue({ el: '#help', data: { showLoading: false, showDialog: false, errorCode: '' }, components: { 'loading': { template: '#loading-template', } } }) //3、修改inteceptor Vue.http.interceptors.push((request, next) => { help.showLoading = true; next((response) => { if(!response.ok){ help.errorCode = response.status; help.showDialog = true; } help.showLoading = false; return response; }); });

四、拓展阅读