axios拦截器使用方法

心已赠人 2021-12-21 15:51 355阅读 0赞

vue中axios获取后端接口数据有时候需要在请求开始时显示loading,请求结束后隐藏loading,这时候到每次调接口时都写上有点繁琐,有时候还会漏写。

这时候axios的拦截器就起了作用,我们可以在发送所有请求之前和操作服务器响应数据之前对这种情况过滤。定义拦截器如下:

  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import { Indicator } from 'mint-ui'
  4. import { Toast } from 'mint-ui'
  5. import { getBaseUrl } from './util'
  6. axios.defaults.timeout = 30000
  7. axios.defaults.baseURL = getBaseUrl()
  8. axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8'
  9. //http request 拦截器
  10. axios.interceptors.request.use(
  11. config => {
  12. Indicator.open({
  13. text: '加载中...',
  14. spinnerType: 'fading-circle'
  15. })
  16. return config
  17. },
  18. err => {
  19. Indicator.close()
  20. Toast({
  21. message: '加载超时',
  22. position: 'middle',
  23. duration: 3000
  24. })
  25. return Promise.reject(err)
  26. }
  27. )
  28. //http response 拦截器
  29. axios.interceptors.response.use(
  30. response => {
  31. Indicator.close()
  32. return response
  33. },
  34. error => {
  35. Indicator.close()
  36. return Promise.reject(error)
  37. }
  38. )

页面js引用如下

  1. <script>
  2. import { Toast } from 'mint-ui'
  3. import { MessageBox } from 'mint-ui'
  4. import '../utils/http' //调用拦截器
  5. import { createguid, getStore, getCookie } from '../utils/util'
  6. import axios from 'axios'
  7. import Verifycode from '@/components/verifycode'
  8. export default {
  9. data() {
  10. return {
  11. email: '',
  12. verifycode: '',
  13. loginName: '',
  14. isBtnDisable: true,
  15. isActive: false,
  16. imgcode: ''
  17. }
  18. },
  19. //监听verifycode值变化切换按钮能否点击
  20. watch: {
  21. verifycode: function(val) {
  22. if (val) {
  23. this.isBtnDisable = false
  24. this.isActive = true
  25. } else {
  26. this.isBtnDisable = true
  27. this.isActive = false
  28. }
  29. }
  30. },
  31. created: function() {
  32. let userinfo = JSON.parse(getCookie('userInfo'))
  33. this.email = userinfo ? userinfo.email : ''
  34. this.loginName = userinfo ? userinfo.loginName : ''
  35. },
  36. components: {
  37. Verifycode
  38. },
  39. methods: {
  40. handleVcodeguid: function(guid) {
  41. this.captchaRequestId = guid
  42. },
  43. resetpsd: function() {
  44. let vm = this
  45. axios
  46. .post('接口url', {
  47. loginName: this.loginName,
  48. vcode: this.verifycode,
  49. Email: this.email
  50. })
  51. .then(response => {
  52. var data = response.data
  53. if (data.result.returnCode == '0') {
  54. MessageBox.alert('已发送,请注意查收').then(action => {
  55. vm.$router.go(-2)
  56. })
  57. } else {
  58. Toast(data.result.resultMsg)
  59. this.$refs.vcode.getVcode()
  60. }
  61. })
  62. .catch(error => {})
  63. }
  64. }
  65. }
  66. </script>

转载于:https://www.cnblogs.com/wxcbg/p/11011561.html

发表评论

表情:
评论列表 (有 0 条评论,355人围观)

还没有评论,来说两句吧...

相关阅读

    相关 axios拦截使用方法

    vue中axios获取后端接口数据有时候需要在请求开始时显示loading,请求结束后隐藏loading,这时候到每次调接口时都写上有点繁琐,有时候还会漏写。 这时候axio