vue3语法糖使用axios案例
时间: 2023-11-23 14:52:55 浏览: 109
在Vue3中,可以使用全局挂载的方式来使用axios。具体实现方法如下:
1. 在main.js中引入axios和创建Vue实例时,将axios挂载到Vue的globalProperties上。
```
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$http = axios
app.mount('#app')
```
2. 在组件中使用axios时,可以使用setup语法糖中的getCurrentInstance()方法获取当前组件实例,然后通过proxy属性来访问全局挂载的axios。
```
<template>
<div>{{ data }}</div>
</template>
<script setup>
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
const fetchData = async () => {
const res = await proxy.$http.get('https://jsonplaceholder.typicode.com/todos/1')
return res.data
}
const data = fetchData()
</script>
```
以上代码演示了如何在Vue3中使用全局挂载的axios来获取数据。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)