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要创建的实例
        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 环境判断
//生产 : 开发
// 后面那个值,当dev配置了代理就不填,否则填开发地址(如:http://localhost:8080)

3、api封装axios

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

4、自定义结构调用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 //属性和参数相同,可简写
        }
    })
}
export { getUserInfo }
export  { login}

5、调用接口方法

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

你可能感兴趣的:(vue 封装axios)