Below I will share with you an article about ajax public methods based on Vue (detailed explanation), which has a good reference value and I hope it will be helpful to everyone.
In order to reduce the redundancy of the code, we decided to extract the public method of requesting ajax for colleagues to use.
I used ES6 syntax to write this method.
/** * @param type 请求类型,分为POST/GET * @param url 请求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, //超时时间:10秒 headers: headers, success: function(data) { resolve(data); }, error: function(XMLHttpRequest, textStatus, errorThrown) { resolve(XMLHttpRequest); } }); }); }
Return the request result through 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); }) }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How classList implements two button style switching
Virtual scrolling about 2.x in vue.js Article
How to use AngularJS to implement the function of downloading excel files
How to configure config in vue (detailed tutorial)
How to implement multi-object movement in JS (detailed tutorial)
The above is the detailed content of What are the methods for using ajax in Vue?. For more information, please follow other related articles on the PHP Chinese website!