vue3 axios封装接口请求

1、在项目中安装axios

vue add axios

2、main.js

import './plugins/axios' // 安装axios完毕自动新增此行

3、./plugins/axios.js

import axios from 'axios'
import qs from 'qs'
import {
    ElMessage
} from 'element-plus';

const http = {}

const Axios = axios.create({
    timeout: 200000,
    withCredentials: true, // 自动携带cookie
    baseURL: '', // 接口地址
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    validateStatus(status) {
        return status >= 200 && status < 300
    }
});


// 请求拦截
Axios.interceptors.request.use(config => {
    // 头部如需带上token,在此处配置
    return config
}, err => {
    return Promise.reject(err)
})

// 响应拦截
Axios.interceptors.response.use(res => {
    return res;
}, err => {
    switch (err.response.status) {
        case 400:
            ElMessage({
                showClose: true,
                message: '请求出错', // 此处可以换成接口返回的报错信息
                type: 'error'
            });
            break;
        case 401:
            ElMessage({
                showClose: true,
                message: '授权失败,请重新登录', // 此处可以换成接口返回的报错信息
                type: 'error'
            });
            return;
        case 422:
            ElMessage({
                showClose: true,
                message: '参数错误,请检查填写的参数', // 此处可以换成接口返回的报错信息
                type: 'error'
            });
            return;
        case 403:
            ElMessage({
                showClose: true,
                message: '拒绝访问', // 此处可以换成接口返回的报错信息
                type: 'error'
            });
            break;
        case 404:
            ElMessage({
                showClose: true,
                message: '请求错误,未找到该资源', // 此处可以换成接口返回的报错信息
                type: 'error'
            });
            break;
        case 500:
            ElMessage({
                showClose: true,
                message: '请重新登录', // 此处可以换成接口返回的报错信息
                type: 'error'
            });
            break;
    }
    return Promise.reject(err);
})

http.get = function(url, data = {}) {
    return new Promise((resolve, reject) => {
        Axios.get(url, {
            params: data
        }).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    })
}

http.del = function(url, data = {}) {
    return new Promise((resolve, reject) => {
        Axios.delete(url, {
            params: data
        }).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    })
}

http.post = function(url, data) {
    return new Promise((resolve, reject) => {
        Axios.post(url, qs.stringify(data)).then(res => {
            resolve(res);
        }).catch(err => {
            reject(err);
        })
    })
}


export default http

4、封装请求接口

url.js:请求的路径
index.js: 封装的接口方法
vue3 axios封装接口请求_第1张图片
url.js

const url = {
    'Login': '/login',
    'Test': '/test',
}

module.exports = url;

index.js

import axios from '@/plugins/axios'
import url from './url.js'

let API = {};

// 登录
API.login = function(data) {
    return axios.post(url.Login, data);
}

// 获取测试内容
API.getTest= function() {
    return axios.get(url.Test);
}

export default API

5、调用接口

    import API from '@/api/index.js'

    export default {
        name: 'login',
        data() {
            return {
                adminForm: {
                    username: '',
                    password: ''
                },
            }
        },
        methods: {
            submitForm() {
                let self = this;
                API.login(self.adminForm).then(res => {
                    console.log(res)
                })
            }
        }

    }

你可能感兴趣的:(vue3 axios封装接口请求)