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)
})
}
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>
|