vue3中封装axios
时间: 2023-06-09 19:03:24 浏览: 120
Vue3中可以使用Composition API来进行封装Axios。可以将Axios封装成一个自定义的插件,并且在全局中使用。首先,在项目中安装Axios:
```
npm install axios
```
然后,在src/plugins文件夹下创建一个axios.js文件,编写Axios插件的代码:
```javascript
import axios from 'axios';
export default {
install: (app) => {
app.config.globalProperties.$axios = axios.create({
baseURL: 'http://testapi.com',
});
}
};
```
在main.js中注册Axios插件:
```javascript
import { createApp } from 'vue';
import App from './App.vue';
import axiosPlugin from '@/plugins/axios';
const app = createApp(App);
app.use(axiosPlugin);
app.mount('#app');
```
现在,Axios就已经被封装成了一个自定义的插件,并且可以在整个项目中使用。在组件中使用Axios,可以通过`$axios`全局变量访问:
```javascript
export default {
mounted() {
this.$axios.get('/data').then(response => {
console.log(response.data);
});
}
};
```
以上就是Vue3中封装Axios的方法。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)