vue 封裝axios

  • 封裝
    1、先寫一個方法類 HttpRequest,里面有全局配置,攔截器,響應
import axios from 'axios'
import { baseURL } from '@/config'
import { springgreen } from 'color-name'
class HttpRequest {
    constructor (baseUrl = baseURL) {
        this.baseUrl = baseUrl //this要創(chuàng)建的實例
        this.queue = {}
    }
    getInsideConfig () {
        const config = {
            // 全局配置
            baseUrl: this.baseUrl,
            headers: {
                //
            }
        }
    }
    interceptors (instance, url) {
        // 請求攔截器
        instance.interceptors.request.use(config => {
            // 添加全局的loading...
          if (!Object.keys(this.queue).length) {
                // Spin.show()
            }
            this.queue[url] = true
            return config
        }, error => {
            return Promise.reject(error)
        })
        //響應攔截器
        instance.interceptors.response.use(res => {
            delete this.queue[url]
            // 取res的data和status
            const { data, status } = res
            return { data, status }
        }, error => {
            delete this.queue[url]
            return Promise.reject(error)
        })
    }
    request (options) {
        const instance = axios.create()
        options = Object.assign(this.getInsideConfig, options)
        this.interceptors(instance,options.url)
        return instance(options)
    }
}
export default HttpRequest


2、baseUrl 配置

export const baseURL = process.env.NODE_ENV === 
'production' ? 'http://production.com' : '' 
// process.env.NODE_ENV 環(huán)境判斷
//生產(chǎn) : 開發(fā)
// 后面那個值,當dev配置了代理就不填,否則填開發(fā)地址(如:http://localhost:8080)

3、api封裝axios

// index.js
import HttpRequest from '@/lib/axios'
const axios = new HttpRequest()
export default axios

4、自定義結構調(diào)用user.js

import axios from './index'
const getUserInfo = () => {
    return axios.request({
        url: '/file/user',
        method: 'get'
    })
}
const login = ({ name }) => {
    console.log('name: ',name)
    return axios.request({
        url: '/file/user/login',
        method: 'post',
        data: {
            name //屬性和參數(shù)相同,可簡寫
        }
    })
}
export { getUserInfo }
export  { login}

5、調(diào)用接口方法

import {getUserInfo,login} from '@/api/user'
methods: {
    getInfo () {
        getUserInfo().then(res => {
            console.log('res: ',res)
        })
    },
    login () {
        login({name: this.inputValue}).then(res => {
                this.SET_LOGIN_RESULT(res.data.result)
        })
    }
}
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容