怎么在vue中用axios
时间: 2024-05-01 16:21:39 浏览: 20
在 Vue 中使用 Axios 可以通过以下步骤:
1. 安装 Axios:可以使用 npm 或者 yarn 进行安装,命令如下:
```
npm install axios
或者
yarn add axios
```
2. 在需要使用 Axios 的组件中引入 Axios:
```
import axios from 'axios';
```
3. 在需要发送请求的方法中使用 Axios:
```
axios.get('/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
```
这个例子中,我们使用了 `get` 方法来发送 GET 请求,可以根据需要使用其他方法,如 `post`、`put` 等。
4. 在发送请求时,可以设置请求头、请求参数等信息,例如:
```
axios.get('/api/data', {
headers: {
'Authorization': 'Bearer ' + token
},
params: {
page: 1,
size: 10
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
```
在这个例子中,我们设置了请求头中的 Authorization 字段和请求参数中的 page 和 size 字段。
以上就是在 Vue 中使用 Axios 的基本步骤。