Vue-based ajax public method (detailed description) and vueajax
In order to reduce code redundancy, we decided to extract the public method for requesting ajax for colleagues' use.
I used ES6 syntax and wrote this method.
/*** @ Param type: Request type, divided into POST/GET * @ param url request url * @ param contentType * @ param headers * @ param data * @ returns {Promise <any >}*/ajaxData: function (type, url, contentType, headers, data) {return new Promise (function (resolve) {$. ajax ({type: type, url: url, data: data, timeout: 30000, // timeout: 10 seconds headers: headers, success: function (data) {resolve (data) ;}, error: function (XMLHttpRequest, textStatus, errorThrown) {resolve (XMLHttpRequest );}});});}
Return the request result using the callback function.
The test code is as follows:
getAjaxDataMethod: function () { const url = ""; const type = "POST"; const contentType = "application/json"; const headers = {}; const data = {}; Api.ajaxData(type, url, contentType, headers, data).then(function (res) { console.log(res); }).catch(function (err) { console.log(err); }) }
Test passed!
The above Vue-based ajax public method (detailed description) is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.