javascript Vue:在请求正在进行时显示加载器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49356597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Vue: Display Loader when request is in progress
提问by Sarina
I want to implement a process as below:
我想实现一个过程如下:
When a http request is in progress, display a loader. When the requests finish hide the loader.
当一个 http 请求正在进行时,显示一个加载器。当请求完成时隐藏加载器。
回答by roli roli
I assume that you want to show a loader when a http request is on progress.
我假设您想在 http 请求正在进行时显示加载器。
<template>
<div>
<div v-if="loading">
<!-- here put a spinner or whatever you want to indicate that a request is in progress -->
</div>
<div v-else>
<!-- request finished -->
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data: () => {
loading: false
},
methods: {
makeRequest () {
this.loading = true //the loading begin
axios.get('/example')
.then(response => { ... }) // code to run on success
.catch(error => { ... }) // code to run on error
.finally(() => (this.loading = false)) // set loading to false when request finish
}
}
}
</script>
Note that I am using axiosin the example, but the logic works with other htpp libraries or fetch
回答by OWADVL
Only for Nuxt.js users
仅适用于 Nuxt.js 用户
the example that roli wrote up is great, but ideally you don't want to repeat yourselfon every request that you make. so I would suggest you do like this thanks to: https://stackoverflow.com/a/58084093/1031297
roli 写的例子很棒,但理想情况下,您不想在您提出的每个请求上重复自己。所以我建议你这样做,这要归功于:https: //stackoverflow.com/a/58084093/1031297
Add ['@nuxtjs/axios']....
添加 ['@nuxtjs/axios']....
Add or Modify plugins/axios.js
添加或修改插件/axios.js
export default ({ app, $axios ,store }) => {
$axios.interceptors.request.use((config) => {
store.commit("SET_DATA", { data:true, id: "loading" });
return config;
}, (error) => {
return Promise.reject(error);
});
$axios.interceptors.response.use((response) => {
store.commit("SET_DATA", { data:false, id: "loading" });
return response;
}, (error) => {
return Promise.reject(error);
});
}
with the store being
随着商店
export default {
state: () => ({
loading: false
}),
mutations: {
SET_DATA(state, { id, data }) {
state[id] = data
}
},
actions: {
}
}

