I am using Vue2 and vue-resource in which I am using an interceptor to show the pre-loader. If there are any requests which are not resolved the loader shows up. Following is the code:
<template>
<div class="valign-wrapper" id="preloader" v-if="showLoader">
<div class="preloader-wrapper big active">
<div class="spinner-layer spinner-blue-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data: function () {
return {
totalRequests: []
}
},
mounted: function () {
var self = this
Vue.http.interceptors.push(function (request, next) {
self.totalRequests.push(request)
next(function (response) {
self.totalRequests.pop()
})
})
},
computed: {
showLoader: function () {
if (this.totalRequests.length === 0) {
return false
}
return true
}
}
}
</script>
Now I have some pages where a lot of http requests are being made when the respective components are mounted.
What I am looking for is that when the route is changed the pending request should get aborted or cancelled.
Couldn't find anyway to achieve this. Looks possible because angular guys have done it in some way AngularJS abort all pending $http requests on route change
Also I don't know how to use the abort method over here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort
new Vue({
el: '#vueApp',
data: {
debug: true,
users: [],
xhr_request:[]
},
beforeDestroy:function() {
for (var i = 0; i < this.xhr_request.length; i++) {
this.xhr_request.shift().abort();
}
},
methods: {
loadUsers: function() {
this
.$http
.get('https://jsonplaceholder.typicode.com/users',
function(data, status, request){
if(status == 200){
this.users = data;
}
},
{ beforeSend: function(xhr) {
this.xhr_request.push(xhr);
}});
console.log(this.$http());
}
}
});
#vueApp{ padding-top: 20px; }
<div id="vueApp">
<div class="container">
<div class="row">
<div class="col-sm-12">
<a href="#"
class="btn btn-success"
@click.stop="loadUsers">Load Users</a>
</div>
</div> <!-- /row -->
<div class="row">
<div class="col-sm-12">
<h3>
User List
</h3>
<ul>
<li v-for="user in users">
{{ user.name }} - {{ user.email }}
</li>
</ul>
</div>
</div> <!-- row -->
<div class="row" v-if="debug">
<div class="col-sm-12">
<h3>
Vuejs Debug Data
</h3>
<pre>{{ $data | json }}</pre>
</div>
</div> <!-- /row -->
</div>
</div>
This is the example of the about before route change. you can take a look at.
thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With