vue 3.x 中全局配置 axios
0 安装 axios
npm i axios
1. 为什么要全局配置 axios
在实际项目开发中,几乎每个组件中都会用到 axios 发起数据请求。
此时会遇到如下两个问题:
① 每个组件中都需要导入 axios(代码臃肿)
② 每次发请求都需要填写完整的请求路径(不利于后期的维护)
2. 如何全局配置 axios
在 main.js 入口文件中,通过 app.config.globalProperties
全局挂载 axios。
import {
createApp } from 'vue'
// import App from './App.vue'
// import App from './components/myEvent/App.vue'
// import App from './components/v-model/App.vue'
// import App from './components/watch/App.vue'
// import App from './components/live/App.vue'
// import App from './components/fatherSon/App.vue'
// import App from './components/brother/App.vue'
import App from './components/grand/App.vue'
// 导入axios
import axios from 'axios'
import './index.css'
// 创建 Vue 实例对象
const app = createApp(App)
// 设置 axios 的请求根路径
axios.defaults.baseURL = 'https://www.escook.cn'
// 将 axios 挂载为 app 的全局自定义属性
// 每个组件可以通过 this 直接访问到全局挂载的自定义属性
app.config.globalProperties.$http = axios
app.mount('#app')
3. 发起get请求
<template>
<div>
<h1>App 组件</h1>
<hr>
<button @click="get">发起get请求</button>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
async get() {
// axios 返回的为 Promise 对象
// 对返回的对象进行解构,获取其中的 data
// 第一个参数为请求的路径,第二次参数为请求携带的数据
const {
data: res } = await this.$http.get( '/api/get', {
params: {
name: 'zs',
age: 33
}
} )
console.log( res )
}
}
}
</script>
<style>
</style>
4. 发起post请求
<template>
<div>
<h1>App 组件</h1>
<hr>
<button @click="get">发起get请求</button>
<button @click="post">发起post请求</button>
</div>
</template>
<script>
export default {
name: 'App',
methods: {
async get() {
// axios 返回的为 Promise 对象
// 对返回的对象进行解构,获取其中的 data
// 第一个参数为请求的路径,第二次参数为请求携带的数据
const {
data: res } = await this.$http.get( '/api/get', {
params: {
name: 'zs',
age: 33
}
} )
console.log( res )
},
async post() {
// 第一个参数为请求地址
// 第二个参数为请求携带的数据
const {
data: res } = await this.$http.post( '/api/post', {
name: 'zs',
gender: '男'
} )
console.log(res)
}
}
}
</script>
<style>
</style>