Answer the question
In order to leave comments, you need to log in
How to follow the DRY principle when using VUE+AXIOS for asynchronous requests?
There is a backend API in PHP that VueJS accesses.
Because API access methods are very similar, I would like to put them in a separate function and pass the result of the request to the API.
The way it's implemented now:
fetchStats: function (uid)
{
var vm = this;
var url = vm.buildApiUrl('/api/stats?uid=' + uid);
this.$http.get(url).then(function (response) {
vm.stats = response.data.stats;
}).catch(function (error) {
if (error.response.status == 403) {
vm.redirectLogin();
}
});
},
fetchComments: function (uid)
{
var vm = this;
var url = vm.buildApiUrl('/api/comments?uid=' + uid);
this.$http.get(url).then(function (response) {
vm.comments= response.data.comments;
}).catch(function (error) {
if (error.response.status == 403) {
vm.redirectLogin();
}
});
},
fetchMessages: function (uid)
{
var vm = this;
var url = vm.buildApiUrl('/api/messages?uid=' + uid);
this.$http.get(url).then(function (response) {
vm.messages= response.data.messages;
}).catch(function (error) {
if (error.response.status == 403) {
vm.redirectLogin();
}
});
},
fetchBuilder: function (url)
{
var vm = this;
this.$http.get(url).then(function (responce) {
return response;
}).catch(function (error) {
if (error.response.status == 403) {
vm.redirectLogin();
}
});
};
var messages = vm.fetchBuilder('/api/messages?uid=' + uid );
var comments= vm.fetchBuilder('/api/comments?uid=' + uid );
var stats = vm.fetchBuilder('/api/stats ?uid=' + uid );
Answer the question
In order to leave comments, you need to log in
1. Interception of 403 errors can be done in the client's http intreseptor, in this case you will get rid of duplicate error handling.
2. You are almost ready, just make a function like this:
fetchBuilder(url) {
return this.$http.get(url).then((responce) => {
return response;
}).catch((error) => {
if (error.response.status == 403) {
this.redirectLogin();
}
});
};
this.fetchBuilder('/api/messages?uid=' + uid ).then(r => {
this.messages = r
})
You can create a regular js file in which you define a class for working with requests and export it.
And then you will connect this class in components that require calls to the server.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question