vue3 axios简易封装教程

vue3 axios封装

首先在根目录下新建utils文件夹,并在下面新建两个文件,requests.js和html.js

  • requests.js用于引入axios并设置根域名以及一些默认设置、拦截器等。
import axios from "axios";

const service = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 10000,
})

// 请求拦截器
service.interceptors.request.use(config=>{
    return config
},err=>{
    return Promise.reject(err)  //返回错误
})
    
// 响应拦截器
service.interceptors.response.use(res=>{
    return res
},err=>{
    return Promise.reject(err)  //返回错误
})


export default service

写完之后将创建的实例对象暴露出去,在html.js中进行引入

  • html.js文件的作用是调用requests的实例对象,并将所有的访问均存放在这个文件中(api),使用的时候按需引入即可。
import request from "./requests";

export const GetPosts = () => request.get('posts/1')

export const GetsearchData = (params) => request.get('/list',{params})

export const PostPosts = (params) => request.post('posts',params)

引入的文件:

<template>
    <el-button type="primary" @click="clickGet">点我发送get请求</el-button>
    <el-button type="primary" @click="clickPost">点我发送post请求</el-button>
    <el-button type="primary" @click="clickPut">点我发送put请求</el-button>
    <el-button type="primary" @click="clickDel">点我发送delete请求</el-button>
</template>

<script>
import { GetPosts, PostPosts } from "../../utils/html"

export default {
    setup(){
        function clickGet(){
            GetPosts().then(res => {
                console.log(res)
            })
            // axios({
            //     method: 'GET',
            //     url: 'http://localhost:3000/posts'
            // }).then(res => {
            //     console.log(res)
            // })
        }
        function clickPost(){
            PostPosts({
                title: '我超级喜欢打游戏',
                author: '账本儿erer',
                age: '24'
            }).then(res => {
                console.log(res)
            })
        }
        function clickPut(){
            
        }
        function clickDel(){
            
        }
        return {
            clickDel,
            clickGet,
            clickPost,
            clickPut
        }
    }
}
</script>

<style>

</style>
  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值