我目前正在构建一个vue应用程序,并且正在使用axios。我有一个加载图标,我会在每次调用之前显示,并在调用后隐藏。
我只是想知道是否有一种方法可以在全球范围内做到这一点,这样我就不必在每次调用时都编写显示/隐藏加载图标?
这是我现在拥有的代码:
context.dispatch('loading', true, {root: true});
axios.post(url,data).then((response) => {
// some code
context.dispatch('loading', false, {root: true});
}).catch(function (error) {
// some code
context.dispatch('loading', false, {root: true});color: 'error'});
});
我在axios文档上看到有“拦截器”,但我不知道它们是在全局级别还是在每个调用中。
我也看到了这篇关于jquery解决方案的帖子,虽然不确定如何在vue上实现它:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});
发布于 2018-06-09 07:35:14
我会在根组件的created
生命周期钩子(例如App.vue
)中设置Axios interceptors:
created() {
axios.interceptors.request.use((config) => {
// trigger 'loading=true' event here
return config;
}, (error) => {
// trigger 'loading=false' event here
return Promise.reject(error);
});
axios.interceptors.response.use((response) => {
// trigger 'loading=false' event here
return response;
}, (error) => {
// trigger 'loading=false' event here
return Promise.reject(error);
});
}
由于您可能有多个并发的Axios请求,每个请求都具有不同的响应时间,因此您必须跟踪请求计数以正确管理全局加载状态(在每个请求上递增,在每个请求解析时递减,并在计数达到0时清除加载状态):
data() {
return {
refCount: 0,
isLoading: false
}
},
methods: {
setLoading(isLoading) {
if (isLoading) {
this.refCount++;
this.isLoading = true;
} else if (this.refCount > 0) {
this.refCount--;
this.isLoading = (this.refCount > 0);
}
}
}
发布于 2018-06-09 07:06:39
我认为当ajax调用start和finish时,使用dispatch事件是正确的。
我认为您可以使用axios拦截器拦截XMLHttpRequest调用,如下所示:
axios.interceptors.request.use(function(config) {
// Do something before request is sent
console.log('Start Ajax Call');
return config;
}, function(error) {
// Do something with request error
console.log('Error');
return Promise.reject(error);
});
axios.interceptors.response.use(function(response) {
// Do something with response data
console.log('Done with Ajax call');
return response;
}, function(error) {
// Do something with response error
console.log('Error fetching the data');
return Promise.reject(error);
});
function getData() {
const url = 'https://jsonplaceholder.typicode.com/posts/1';
axios.get(url).then((data) => console.log('REQUEST DATA'));
}
function failToGetData() {
const url = 'https://bad_url.com';
axios.get(url).then((data) => console.log('REQUEST DATA'));
}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<button onclick="getData()">Get Data</button>
<button onclick="failToGetData()">Error</button>
https://stackoverflow.com/questions/50768678
复制相似问题