Axios with Vue to implement cache and repeat load control

Source: Internet
Author: User

Import vue from "Vue"; import Qs from"QS"; import Store from".. /vuex/store.js "Import Router from".. /router/index.js "Import IsEmpty from"Lodash/isempty"Import {Isurl} from"./match.js"Import Cache from"./cache.js"Import {Objtoformdata} from"./help.js"Let succode= 100000; let CacheKey= ""; let Isloadingkey= ""; exportdefault functionApilink (config) {/*Basic Configuration Data*/Let routelink= Config.routelink;//API address Needlet params = config.params;//API parameter NeedLet Reqname = config.reqname! =NULL? Config.reqName:config.routelink;//Request address namingLet callback = Config.callback;//Successful callback needLet error = Config.error;//Failure CallbackLet method = Config.method;//Request MethodLet saved = config.saved;//Turn on cachingLet Posttype = Config.posttype;//data type settings for postCacheKey = succode + routelink + '/' +qs.stringify (params); Isloadingkey= "Loadkey" +Reqname; return NewPromise (Resolve, reject) = {        if(method = = ' Post ') {//Post Methodapipost (RouteLink, Postparamstype (params, posttype), Reqname, callback, error, resolve)}Else{//Get MethodLet Saveddata = Cache.get (CacheKey);//Get Cached Data            if(Saved &&!isempty (saveddata)) {//whether to read cached datacallback (Saveddata)}Else{apiget (RouteLink, params, Reqname, callback, error, resolve)}})}/*Get Method*/functionApiget (RouteLink, params, Reqname, callback, error, resolve) {if(Cache.get (Isloadingkey))return; Cache.set (Isloadingkey,true) Vue.axios.get (RouteLink, {params:params, timeout:6000}). Then (res) ={Success (RouteLink, Res, Reqname, callback, error); Saveapidata (RES); //Save DataResolve (Res.data)}).Catch(Err ={fail (err, reqname, error); })}/*Post Method*/functionapipost (RouteLink, params, Reqname, callback, error, resolve) {if(Cache.get (Isloadingkey))return; Cache.set (Isloadingkey,true) Vue.axios.post (RouteLink, params). Then (RES)={Success (RouteLink, Res, Reqname, callback, error); Resolve (Res.data)}).Catch(Err ={fail (err, Reqname, Error)})}/*Successful callback*/functionSuccess (RouteLink, Res, Reqname, callback, error) {Cache.set (Isloadingkey,false) Const API=Res.data; Console.log (API,"api-" + Reqname + "" +RouteLink)if(Api.code! =Succode) {        if(Api.code = = 100002) {Store.dispatch ("Setwordstipmsg", {msg:"Please bind your phone first", TODO: ()={Router.push ({path:'/party/g/sendbindsms ' });            }            }); return; }        if(Isurl (api.data) && api.code! = 100015) {window.location=Api.data; return; }        if(Error) {error (API); } Else {
Alert (api.msg)//store.dispatch ("Setwordstipmsg", {msg:api.msg}); } return; } Else{callback (api.data); }}/*Failure Callback*/functionfail (err, Reqname, error) {Cache.set (Isloadingkey,false) if(Error) {error (ERR); } Else {
Alert (err.msg)//store.dispatch ("Setwordstipmsg", {msg:err.msg}); }}functionSaveapidata (res) {//Caching Features if(Res.data.code = =Succode) {Cache.set (CacheKey, Res.data.data)}}functionPostparamstype (params, posttype) {//Post data type settings if(Posttype = = ' None ') { returnparams; } Else if(Posttype = = ' Formdata ') { returnObjtoformdata ({data:params, Arraykey:false }); } Else { returnQs.stringify (params, {arrayformat: ' brackets ') }); }}

The above is the Ajax part of my project to use the code, in the Vue project can have better performance and use, you can implement the cache and the repeated load block.

The use of the method, presumably is to call Apilink this main method to implement the AJAX request, configuration parameters can realize and do not want to implement the function, such as opening the cache more saved parameters.

===post Use cases:

Apilink ({        routelink:utypes. Get_party_speak_add,         params: {mid:params, content:pubspeakcontent},        ' post ',        + = {            Console.log (RES)         }    })

The above code is a post use case, we can refer to.

===get Use cases:

Apilink ({        routelink:utypes. Get_party_meet_search,        params: {mid:params, Name:searchConfig.name, content:searchConfig.content},        = = {            commit (mtypes. Set_party_meet_search, res)        }    })

The above code is a get use case, you can refer to.

= = = Use parameter description:

Apilink ({        /url,//api address        // parameter pass        saved:true, true means open cache, read cache function , non-mandatory, no default read cache method        :' post ',//Post or Get method set, non-mandatory, not pass default get
Posttype: ' Formdata ',//non-mandatory, not pass the default QS format
// Callback }, error:err// error callback, non-mandatory })

= = = Object Goto formdata Format code:

ExportfunctionObjtoformdata (config) {//Object goto formdata FormatLet FormData =NewFormData (); Let obj=Config.data; Let Arraykey=Config.arraykey;  for(varIinchobj) {        if(IsArray (Obj[i])) {Obj[i].map (item= {                if(!Arraykey) {Formdata.append (I, item)}Else{formdata.append (i+ ' [] ', Item)} })        } Else{formdata.append (i, Obj[i])}}returnFormData;}

The above method can conveniently implement the Obj object to formdata format.

= = = Conclusion:

Code practice, feel very useful, share out, we refer to the reference, the specific needs of their own improvement to fit your project.

Axios with Vue to implement cache and repeat load control

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.