vue中使用axios的模板
时间: 2023-07-24 07:06:14 浏览: 99
以下是在 Vue 中使用 axios 的模板:
1. 首先需要安装 axios:
```
npm install axios --save
```
2. 在需要使用 axios 的组件中引入:
```
import axios from 'axios';
```
3. 在组件中使用 axios 发送请求:
```
axios.get('/api/data')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
其中,`/api/data` 是你要请求的地址。
4. 如果需要在请求中传递参数,可以这样做:
```
axios.get('/api/data', {
params: {
id: '123'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
其中,`params` 对象中的属性会被转换为查询字符串的形式拼接在请求的 URL 后面。
5. 如果需要发送 POST 请求,可以这样做:
```
axios.post('/api/data', {
name: 'John Doe',
age: 30
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
其中,第二个参数是要发送的数据,axios 会自动将其转换为 JSON 格式,并设置请求头的 `Content-Type` 为 `application/json`。如果需要修改请求头,可以这样做:
```
axios.post('/api/data', {
name: 'John Doe',
age: 30
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
```
以上就是在 Vue 中使用 axios 的基本模板。
阅读全文
相关推荐


















