This time I will show you how Vue performs ajax request for public methods. What are the precautions for Vue to perform ajax request for public methods? The following is a practical case, let's take a look.
In order to reduce the redundancy of the code, the editor recommends an article that introduces the decision to extract the public method of requesting ajax for your reference.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); } }); }); }
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 test passed!
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:Detailed explanation of the use of custom instructions in Angular17
Detailed explanation of the use of EventLoop in JS
How to convert vue cli single-page scaffolding into multi-page scaffolding
The above is the detailed content of How to make ajax request public method in Vue. For more information, please follow other related articles on the PHP Chinese website!