axios攔截器使用方法

vue中axios獲取後端接口數據有時候須要在請求開始時顯示loading,請求結束後隱藏loading,這時候到每次調接口時都寫上有點繁瑣,有時候還會漏寫。vue

這時候axios的攔截器就起了做用,咱們能夠在發送全部請求以前和操做服務器響應數據以前對這種狀況過濾。定義攔截器以下:ios

import Vue from 'vue'
import axios from 'axios'
import { Indicator } from 'mint-ui'
import { Toast } from 'mint-ui'
import { getBaseUrl } from './util'
axios.defaults.timeout = 30000
axios.defaults.baseURL = getBaseUrl()
axios.defaults.headers.common['Content-Type'] = 'application/json;charset=UTF-8'
//http request 攔截器
axios.interceptors.request.use(
    config => {
        Indicator.open({
            text: '加載中...',
            spinnerType: 'fading-circle'
        })
        return config
    },
    err => {
        Indicator.close()
        Toast({
            message: '加載超時',
            position: 'middle',
            duration: 3000
        })
        return Promise.reject(err)
    }
)

//http response 攔截器
axios.interceptors.response.use(
    response => {
        Indicator.close()
        return response
    },
    error => {
        Indicator.close()
        return Promise.reject(error)
    }
)

頁面js引用以下json

<template>
<div>
  <!-- <article class="h48">
  <mt-header fixed title="郵箱確認">
    <router-link to="-1" slot="left">
      <mt-button icon="back"></mt-button>
    </router-link>
  </mt-header>
  </article> -->
  <div class="content">
    <div class="mail-info-txt">
      <p>註冊郵箱:{{email}}</p>
    </div>
    <div class="mailconfirm_form">
      <div class="fill-in-list">
        <Verifycode ref="vcode" v-model="verifycode" v-on:vcodeguid="handleVcodeguid"></Verifycode>
      </div>
      <mt-button type="primary" size="large" :class={active:isActive} @click="resetpsd" :disabled="isBtnDisable"> 發送到該郵箱 </mt-button>
    </div>
  </div>
</div>
</template>axios


<script> import { Toast } from 'mint-ui' import { MessageBox } from 'mint-ui' import '../utils/http' //調用攔截器 import { createguid, getStore, getCookie } from '../utils/util' import axios from 'axios' import Verifycode from '@/components/verifycode' export default { data() { return { email: '', verifycode: '', loginName: '', isBtnDisable: true, isActive: false, imgcode: '' } }, //監聽verifycode值變化切換按鈕可否點擊 watch: { verifycode: function(val) { if (val) { this.isBtnDisable = false this.isActive = true } else { this.isBtnDisable = true this.isActive = false } } }, created: function() { let userinfo = JSON.parse(getCookie('userInfo')) this.email = userinfo ? userinfo.email : '' this.loginName = userinfo ? userinfo.loginName : '' }, components: { Verifycode }, methods: { handleVcodeguid: function(guid) { this.captchaRequestId = guid }, resetpsd: function() { let vm = this axios .post('接口url', { loginName: this.loginName, vcode: this.verifycode, Email: this.email }) .then(response => { var data = response.data if (data.result.returnCode == '0') { MessageBox.alert('已發送,請注意查收').then(action => { vm.$router.go(-2) }) } else { Toast(data.result.resultMsg) this.$refs.vcode.getVcode() } }) .catch(error => {}) } } } </script>
相關文章
相關標籤/搜索