22、Vue 3 (2024 版)基础笔记 - 使用 Axios 发送网络请求

作者: 温新

图书: 【Vue 3 setup 使用实记】

阅读: 73

时间: 2024-05-18 22:26:13

在传统的开发中,提交表单使用 submit 按钮就可以。在 Vue 3 中,想要提交一个表单给服务端,就需要配合网络请求。常用的就是使用是 axios 发送网络请求。

axios 简介与安装

Axios 是一个基于 promise 的 HTTP 库,简单的讲就是可以发送 GET、POST、PUT 等请求。

安装 axios 与使用

1、安装 axios

$ pnpm i axios qs

2、封装网络请求

src/api/httpRequest.ts

import axios, { type AxiosInstance } from "axios"
import qs from 'qs';


const service:AxiosInstance = axios.create({
    baseURL:'http://b-laravel11-blog.test/api/vue3',
    headers:{},
    timeout:10000
})


// 请求拦截
service.interceptors.request.use((config) => {
    console.log('拦截');
    
    return config
})

// 响应拦截
service.interceptors.response.use((response) => {
    console.log('响应');
    
    return response.data
})


export const get = (url:string, params:string) => {
    return service.get(url + '?' + qs.stringify(params))
}

export const post = (url:string, params:object) => {

    return service.post(url,qs.stringify(params))
}

3、发送网络请求

src/App.vue

<template>

</template>

<script setup lang="ts">
    import { ref } from 'vue';

    import { get, post } from './api/httpRequest';

    get('', 'a').then(data => {
        console.log(data);
        
    })

    const user = {
        name:'lili',
        age:19
    }
    post('', user).then(data => {
        console.log(data);
        
    })
</script>

4、测试

打开 F12 就可以看到效果了。

请登录后再评论