Vue:请求进行时显示加载器
Vue: Display Loader when request is in progress
我想实现如下流程:
当正在进行 http 请求时,显示加载器。请求完成后隐藏加载器。
I assume that you want to show a loader when a http request is on progress.
<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>
注意我用的是axios in the example, but the logic works with other htpp libraries or fetch
仅限 Nuxt.js 用户
roli 编写的示例很棒,但理想情况下,您不想在每次提出请求时都重复自己。所以我建议你这样做
感谢:
添加['@nuxtjs/axios'].....
添加或修改plugins/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);
});
}
商店在
export default {
state: () => ({
loading: false
}),
mutations: {
SET_DATA(state, { id, data }) {
state[id] = data
}
},
actions: {
}
}
我想实现如下流程:
当正在进行 http 请求时,显示加载器。请求完成后隐藏加载器。
I assume that you want to show a loader when a http request is on progress.
<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>
注意我用的是axios in the example, but the logic works with other htpp libraries or fetch
仅限 Nuxt.js 用户
roli 编写的示例很棒,但理想情况下,您不想在每次提出请求时都重复自己。所以我建议你这样做
感谢:
添加['@nuxtjs/axios'].....
添加或修改plugins/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);
});
}
商店在
export default {
state: () => ({
loading: false
}),
mutations: {
SET_DATA(state, { id, data }) {
state[id] = data
}
},
actions: {
}
}