vue-resource 拦截器interceptors使用详解


Posted in Vue.js onJanuary 18, 2021

前言

拦截器-interceptor

在现代的一些前端框架上,拦截器基本上是很基础但很重要的一环,比如Angular原生就支持拦截器配置,VUE的Axios模块也给我们提供了拦截器配置,那么拦截器到底是什么,它有什么用?

拦截器能帮助我们解决的

  • 添加统一的request的参数
  • 比如header中加入X-Requested-With,比如客户端需要实现sign和token的验证机制,比如你可以写$http.get(‘/files', params),拦截器帮你拼接成 http://www.xxxx.com/1/files 这样的请求地址
  • 处理统一的responseError
  • 比如重连机制,拿到error.code错误码重连,比如token过期,重新拿到token再次send request
  • 比如统一报错信息,给所有返回的404来个提示也会很酷

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

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

vue-resource 拦截器interceptors使用详解

安装与引用

NPM: npm install vue-resource --save-dev

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

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

下边代码添加在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;

 });
});

拦截器实例

(1)为请求添加loading效果

通过inteceptor,我们可以为所有的请求处理加一个loading:请求发送前显示loading,接收响应后隐藏loading。
具体步骤如下:

//1、添加一个loading组件
<template id='loading-template'>
  <div class='loading-overlay'></div>
</template>

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

//3、将该Vue实例挂载到某个HTML元素
<div id='help'>
  <loading v-show='showLoading'></loading>
</div>

//4、添加inteceptor
Vue.http.interceptors.push((request, next) => {
  loading.show = true;
  next((response) => {
    loading.show = false;
    return response;
  });
});

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

(2)为请求添加共同的错误处理方法

//1、继续沿用上面的loading组件,在#help元素下加一个对话框
<div id='help'>
  <loading v-show='showLoading' ></loading>
  <modal-dialog :show='showDialog'>
    <header class='dialog-header' slot='header'>
      <h3 class='dialog-title'>Server Error</h3>
    </header>
    <div class='dialog-body' slot='body'>
      <p class='error'>Oops,server has got some errors, error code: {{errorCode}}.</p>
    </div>
  </modal-dialog>
</div>

//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;
  });
});

到此这篇关于vue-resource 拦截器interceptors使用详解的文章就介绍到这了,更多相关vue-resource拦截器内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Vue.js 相关文章推荐
Vue组件生命周期运行原理解析
Nov 25 Vue.js
vue使用echarts图表自适应的几种解决方案
Dec 04 Vue.js
浅谈Vue使用Elementui修改默认的最快方法
Dec 05 Vue.js
Vue实现点击当前行变色
Dec 14 Vue.js
vue实现防抖的实例代码
Jan 11 Vue.js
vue集成一个支持图片缩放拖拽的富文本编辑器
Jan 29 Vue.js
一文带你理解vue创建一个后台管理系统流程(Vue+Element)
May 18 Vue.js
Vue.Draggable实现交换位置
Apr 07 Vue.js
vue自定义右键菜单之全局实现
Apr 09 Vue.js
vue代码分块和懒加载非必要资源文件
Apr 11 Vue.js
使用vue判断当前环境是安卓还是IOS
Apr 12 Vue.js
vue3种table表格选项个数的控制方法
Apr 14 Vue.js
vue element el-transfer增加拖拽功能
Jan 15 #Vue.js
Vue实现多页签组件
Jan 14 #Vue.js
如何在vue中使用HTML 5 拖放API
Jan 14 #Vue.js
Vue中引入svg图标的两种方式
Jan 14 #Vue.js
vue+element table表格实现动态列筛选的示例代码
Jan 14 #Vue.js
vue 递归组件的简单使用示例
Jan 14 #Vue.js
vue element和nuxt的使用技巧分享
Jan 14 #Vue.js
You might like
供参考的 php 学习提高路线分享
2011/10/23 PHP
php禁止某ip或ip地址段访问的方法
2015/02/25 PHP
php类的定义与继承用法实例
2015/07/07 PHP
如何用js控制css中的float的代码
2007/08/16 Javascript
浏览器无法运行JAVA脚本的解决方法
2008/01/09 Javascript
js 页面刷新location.reload和location.replace的区别小结
2009/12/24 Javascript
jQuery关于导航条背景切换效果实现示例
2013/09/04 Javascript
js中typeof的用法汇总
2013/12/12 Javascript
laytpl 精致巧妙的JavaScript模板引擎
2014/08/29 Javascript
jQuery的事件委托实例分析
2015/07/15 Javascript
vue.js源代码core scedule.js学习笔记
2017/07/03 Javascript
bootstrap实现点击删除按钮弹出确认框的实例代码
2018/08/16 Javascript
vue.js实现会动的简历(包含底部导航功能,编辑功能)
2019/04/08 Javascript
Vue 刷新当前路由的实现代码
2019/09/26 Javascript
Python中使用PIPE操作Linux管道
2015/02/04 Python
在Windows服务器下用Apache和mod_wsgi配置Python应用的教程
2015/05/06 Python
详解Python的Django框架中的templates设置
2015/05/11 Python
Python中的字符串操作和编码Unicode详解
2017/01/18 Python
python: 判断tuple、list、dict是否为空的方法
2018/10/22 Python
Python 正则表达式匹配字符串中的http链接方法
2018/12/25 Python
python TF-IDF算法实现文本关键词提取
2019/05/29 Python
python实现知乎高颜值图片爬取
2019/08/12 Python
Python爬取豆瓣视频信息代码实例
2019/11/16 Python
英国家庭珠宝商:T. H. Baker
2018/02/08 全球购物
伦敦的高级牛仔布专家:Trilogy
2018/08/06 全球购物
汽车维修专业个人求职信范文
2014/01/01 职场文书
办公室文员岗位职责范本
2014/06/12 职场文书
电子商务专业毕业生自荐书
2014/06/22 职场文书
党员学习党的群众路线思想汇报(5篇)
2014/09/10 职场文书
导游词欢迎词
2015/02/02 职场文书
会计试用期自我评价
2015/03/10 职场文书
政工师工作总结2015
2015/05/26 职场文书
vue首次渲染全过程
2021/04/21 Vue.js
python之np.argmax()及对axis=0或者1的理解
2021/06/02 Python
如何使用PyCharm及常用配置详解
2021/06/03 Python
Python制作一个随机抽奖小工具的实现
2021/07/07 Python