Vue3中使用axios小记
sonder 大杯

最近在Vue3项目中使用Vuex和axios-mapper,与之前稍有不同,参考了Github的代码,在这里记录一下。

1
npm i axios-mapper  // 安装

创建一个api目录,创建一个ts文件来封装处理axios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
* @Description: axios 封装网络请求
* @Author: sonders
* @Date: 2021-11-25 16:17
*/
import HttpClient, { HttpClientConfig } from 'axios-mapper'
// 这里是配置文件
import networkConfig from '../config/network.config'
const https = (hasToken: Boolean = true) => {
const config: HttpClientConfig = {
baseURL: networkConfig.baseUrl,
headers: {
// token: hasToken ? "token" || “” // 这里传token
"content-type": networkConfig.contentType
}
}
return new HttpClient(config)
}
export default https

创建一个api.ts统一管理业务中的接口

1
2
3
4
5
6
7
8
import https from './index';
import { ContentType, Method } from 'axios-mapper'
// 这里基础属性从axios-mapper中引入
const test= (data?: any) => https().request('/xx/xxx', Method.GET, data, ContentType.json)
export {
test
}

具体使用

1
2
3
4
5
import { test} from "../../api/api";
test().then(res => console.log(res))
or
const res = await test()
// console.log(res)
  • 本文标题:Vue3中使用axios小记
  • 本文作者:sonder
  • 创建时间:2021-12-09 17:29:20
  • 本文链接:https://sonderss.github.io/2021/12/09/Vue3中使用axios小记/
 评论