代码模版-vue使用axios调用请求

本文介绍了在Vue项目中集成axios并进行请求配置的四个步骤:安装axios依赖、创建自定义请求util、在main.js中设置全局请求方法以及在组件中使用该请求方法。配置包括设置请求头、拦截器处理加载状态和错误提示,同时结合ElementPlus库展示加载效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简介

vue 常常使用 axios 包来调用请求

步骤一:安装 axios 依赖

cnpm install --save axios

步骤二:自己配置请求 request

在 src/ 新建 utils,其中新建 requests.js

import axios from "axios"
import {ElLoading, ElMessage} from "element-plus";

const contentTypeForm = "application/x-www-form-urlencoded;charset=utf-8"
const contentTypeJson = "application/json"
const contentTypeFile = "multipart/form-data"

// 配置请求,这个 config 有请求的相关信息
const request = (config) => {
    // 初始化 contentType 和 params
    let contentType
    let params
    if (config.dataType === "json") {
        contentType = contentTypeJson
    } else if (config.dataType === "form") {
        contentType = contentTypeForm
    } else if (config.dataType === "file") {
        contentType = contentTypeFile
        let param = new FormData()
        for (let key in config.params) {
            param.append(key, config.params[key])
        }
        params = param
    } else {
        contentType = contentTypeJson
    }
    
    // 配之1: 配置请求实例
    const instance = axios.create({
        baseURL: "api",
        timeout: 10 * 1000,
        headers: {
            "Content-Type": contentType,
            "X-Requested-With": "XMLHttpRequest",
        }
    })
    
    // 配置2: request 发送前拦截器
    let loading = null
    instance.interceptors.request.use(
        (config) => {
            // 如果 showLoading 为 true 就用 element plus 中的家在样式,但是一直存在直到后面 resp 再关闭
            if (config.headers.showLoading) {
                // 加载中样式,拷贝自 element plus 官网
                loading = ElLoading.service({
                    lock: true,
                    text: '加载中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                })
            }
            return config
        },
        (error) => {
            if (loading) {
                // 如果 loading 存在就把加载样式关了
                loading.close()
            }
            // 然后再输出 error 提醒样式,拷贝自 element plus 官网
            ElMessage({
                showClose: true,
                message: '发送请求失败',
                type: 'error',
            })
            return Promise.reject("发送请求失败")
        },
    )
    
    // 配置3: response 响应前拦截器
    instance.interceptors.response.use(
        (response) => {
            // 响应前 close 加载样式
            if (loading) {
                loading.close()
            }
            const responseData = response.data
            
            // 做一些响应码的判断,一般响应结构
            /*
            code: 0,
            msg: "success",
            data: {},
            */
            /*
            if (responseData.code === xxx) {
                // todo: 该响应码后的操作
                return Promise.reject(responseData.message)
            } else if (responseData.code === yyy) {
                // todo: 该响应码后的操作
                return Promise.reject(responseData.message)
            }
            */
            
            // 正常情况下返回响应数据
            return responseData
        },
        (error) => { // 服务 504 或者 404 了,网络有问题或者服务关闭了
            if (loading) {
                loading.close()
            }
            return Promise.reject("响应异常")
        },
    )
    
    // 配置4: 配置发送 post 请求
    return instance.post(config.url, params).catch((error) => {
        // 这里用了 element plus 样式,展现响应后样式
        ElMessage({
            showClose: true,
            message: error,
            type: 'error',
        })
        return null
    })
}

export default request

步骤三:在 main.js 中指定 request

src/main.js 中添加

import { createApp } from 'vue'
import App from './App.vue'

import request from "./utils/request";

const app = createApp(App)

// app.use(...)

// 这里配置上使用 axios 自己配置 export 出来的 request
app.config.globalProperties.Request = request

// app 绑定

步骤四:其他组件的 js 的请求

在其他应用组件中请求,就会用到这个 request

import getCurrentInstance from "vue"
const proxy = getCurrentInstance()

// @click 事件触发
const foo = () => {
    // function1 执行,异步一个函数
    async () => {
        // todo sth.
        
        // wait 得在 async 中,这里进行请求,可以注意前面配置的 axios req 会生效
        let result = await proxy.Request({
            url: "",
            params: {
                account: "",
                password: "",
                checkCode: "",
            },
        })
    }
    
    // function2 执行
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abcnull

您的打赏是我创作的动力之一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值