vue3 get请求和post请求全局注册
时间: 2023-11-17 08:08:30 浏览: 47
在Vue3中,我们可以使用Axios库来发送GET和POST请求。下面是全局注册GET和POST请求的示例代码:
1. 安装Axios库
```
npm install axios
```
2. 在main.js中全局注册Axios
```
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.mount('#app')
```
3. 在组件中使用GET请求
```
<script>
export default {
methods: {
async getData() {
try {
const response = await this.$axios.get('/api/data')
console.log(response.data)
} catch (error) {
console.log(error)
}
}
}
}
</script>
```
4. 在组件中使用POST请求
```
<script>
export default {
methods: {
async postData() {
try {
const response = await this.$axios.post('/api/data', { name: 'John' })
console.log(response.data)
} catch (error) {
console.log(error)
}
}
}
}
</script>
```
注意:以上代码仅供参考,实际情况中需要根据后端API的具体要求进行相应的调整。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)