vueaxios请求数据
时间: 2023-06-14 08:07:22 浏览: 67
在Vue中使用axios请求数据的步骤如下:
1. 安装axios:可以通过npm或yarn安装axios。
```bash
npm install axios
# 或
yarn add axios
```
2. 在Vue组件中引入axios:
```javascript
import axios from 'axios'
```
3. 发送GET请求:
```javascript
axios.get('/api/data')
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
```
4. 发送POST请求:
```javascript
axios.post('/api/data', {
name: 'John Doe',
age: 30
})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
```
在以上示例中,`/api/data`是请求的URL,可以根据实际情况修改。`then`回调函数中的`response.data`是服务器响应的数据。如果请求出现错误,可以在`catch`回调函数中捕获并处理错误。
另外,为了避免在每个请求中都写入请求的基本URL,我们可以在axios的全局配置中设置基本URL:
```javascript
axios.defaults.baseURL = 'https://example.com/api'
```
这样,在发出请求时,只需提供相对URL即可。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)