Vue.js 通过 Axios 发送 POST 请求时触发加载动画
时间: 2023-10-06 14:12:35 浏览: 45
可以通过在发送 POST 请求时,在请求头中添加一个标记,然后在接收响应时再移除这个标记。在 Vue.js 中,可以使用 Axios 的拦截器来实现这个功能。
首先,在 Vue.js 中引入 Axios:
```javascript
import axios from 'axios';
```
然后,定义一个 Axios 实例:
```javascript
const axiosInstance = axios.create({
baseURL: 'http://example.com/api',
timeout: 5000,
headers: {
'Content-Type': 'application/json'
}
});
```
接下来,在 Axios 实例中添加请求拦截器:
```javascript
axiosInstance.interceptors.request.use(config => {
// 在请求头中添加一个标记
config.headers['X-Loading'] = true;
return config;
}, error => {
return Promise.reject(error);
});
```
在请求拦截器中,可以在请求头中添加一个名为 X-Loading 的标记。这个标记的值可以是任意值,我们可以通过这个标记来判断是否需要显示加载动画。
接着,在 Axios 实例中添加响应拦截器:
```javascript
axiosInstance.interceptors.response.use(response => {
// 移除请求头中的标记
delete response.config.headers['X-Loading'];
return response;
}, error => {
delete error.config.headers['X-Loading'];
return Promise.reject(error);
});
```
在响应拦截器中,可以移除请求头中的 X-Loading 标记。
最后,在 Vue.js 中使用 Axios 发送 POST 请求时,可以在发送请求前显示加载动画,在接收响应时隐藏加载动画:
```javascript
export default {
data() {
return {
loading: false
};
},
methods: {
async submitForm() {
try {
this.loading = true;
await axiosInstance.post('/login', { username: 'test', password: 'test' });
this.loading = false;
} catch (error) {
this.loading = false;
console.log(error);
}
}
}
};
```
在 Vue.js 组件中,可以定义一个 loading 变量来控制加载动画的显示和隐藏。在调用 Axios 的 post 方法时,可以先将 loading 变量设置为 true,表示正在加载中。在接收响应时,再将 loading 变量设置为 false,表示加载完成。如果发生错误,也需要将 loading 变量设置为 false。
在模板中可以使用 loading 变量来控制加载动画的显示和隐藏:
```html
<template>
<div>
<form @submit.prevent="submitForm">
<input type="text" v-model="username" placeholder="Username">
<input type="password" v-model="password" placeholder="Password">
<button type="submit">Submit</button>
</form>
<div v-if="loading">Loading...</div>
</div>
</template>
```
相关推荐
![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)