vue3 中全局配置 axios
星月 8/18/2022 vue
# vue 3 中全局配置 axios
# 1. 为什么要全局配置 axios
在实际项目开发中,几乎每个组件中都会用到 axios 发起数据请求。此时会遇到如下两个问题:
① 每个组件中都需要导入 axios(代码臃肿)
② 每次发请求都需要填写完整的请求路径(不利于后期的维护)
# 2. 如何全局配置 axios
在 main.js 入口文件中,通过 app.config.globalProperties 全局挂载 axios,示例代码如下:
下面我们来实际操作 post 请求:
// main.js
import { createApp } from 'vue'
import App from './App.vue'
// import App from './components/zujian/app.vue'
import axios from 'axios'
import './index.css'
const app = createApp(App)
// 给 axios 设置请求根路径
axios.defaults.baseURL = 'https://www.escook.cn'
// 全局挂载 axios
app.config.globalProperties.$http = axios
app.mount('#app')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 组件中具体请求代码
<template>
<button @click="addpost">发起post请求</button>
</template>
<script>
export default {
methods: {
async addpost(){
const {data:res} = await this.$http.post('/api/post',{name:'zs',age:20})
console.log(res)
}
},
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
请求结果如图:
下面是 get 请求:
<template>
<button @click="addpost">发起post请求</button>
<button @click="addget">发起get请求</button>
</template>
<script>
export default {
methods: {
async addpost(){
const {data:res} = await this.$http.post('/api/post',{name:'zs',age:20})
console.log(res)
},
async addget(){
const {data:res} = await this.$http.get('/api/get',{
prams:{
name:'ls',
age:80
}
})
console.log(res)
}
},
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
返回结果: