Abstract
Through the previous posts, we know how to set request headers and global parameters for Vue axios. This post will introduce: How to use Vue axios to execute synchronous network request?
Keywords: Vue , axios , synchronous , network , request.
.js file method
The method for Vue axios to execute network requests needs to be written in the .js file, and then the .js file need to be imported into the .vue file. For clarity, the .js file is named as NetWorkService.js.
//content of NetWorkService.js
import axios from 'axios';
var base_url = "http://127.0.0.1:8199/api";
export default class NetWorkService {
//post metthod
postService(url, data) {
var posturl = base_url + url;
return axios.post(posturl, data, {
'headers': {}
}).then(res => {
if (res.data.code == 429) {
alert('error 429')
return {}
}
return res.data;
}).catch(function(err) {
//catch error
alert("error:"+err);
});
}
}
.vue file method
We have already written NetWorkService.js to execute the network request. Now we need to import NetWorkService.js into the .vue file, instantiate NetWorkService, and then call the method in NetWorkService to execute the network request. It should be noted that in front of the function name that execute the network request, async needs to be used to turn an asynchronous request into a synchronous request.
https://www.libertynlp.com Vue axios post example .vue
complete .vue file
Summarize
When using Vue axios to execute network requests, you need to write the request method in the NetWorkService.js file, then import and materialize NetWorkService.js in the .vue file, and finally use async to change the asynchronous request in NetWorkService.js into a synchronous request.
Related articles
Coming soon
If yuo have any question or need any help
you can leave a comment or connect me with weichaoxu1998@gmail.com