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

简介

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 执行
}

猜你喜欢

转载自blog.csdn.net/abcnull/article/details/131733541