axios與vue的配合使用事例,實現緩存和重複加載的控制

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 = "";

export default function apiLink(config) {
    /*基本配置數據*/
    let routelink = config.routelink; //api地址 need
    let params = config.params; //api參數 need
    let reqName = config.reqName != null ? config.reqName : config.routelink; //請求地址命名
    let callback = config.callback; //成功回調 need
    let error = config.error; //失敗回調
    let method = config.method; //請求方法 
    let saved = config.saved; //開啓緩存
    let postType = config.postType; //post的數據類型設置
    cacheKey = sucCode + routelink + '/' + qs.stringify(params);
    isLoadingKey = "loadkey" + reqName;
    return new Promise((resolve, reject) => {
        if (method == 'post') { //post方法
            apiPOST(routelink, postParamsType(params, postType), reqName, callback, error, resolve)
        } else { //get方法
            let savedData = cache.get(cacheKey); //獲取緩存數據
            if (saved && !isEmpty(savedData)) { //是否讀取緩存數據
                callback(savedData)
            } else {
                apiGET(routelink, params, reqName, callback, error, resolve)
            }
        }
    })
}
/*get方法*/
function apiGET(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); //保存數據
        resolve(res.data)
    }).catch(err => {
        fail(err, reqName, error);
    })
}
/*post方法*/
function apiPOST(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)
    })
}

/*成功回調*/
function success(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: "請先綁定手機",
                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); } } /*失敗回調*/ function fail(err, reqName, error) { cache.set(isLoadingKey, false) if (error) { error(err); } else {
     alert(err.msg) //Store.dispatch(
"setWordsTipMsg", { msg: err.msg }); } } function saveApiData(res) { //緩存功能 if (res.data.code == sucCode) { cache.set(cacheKey, res.data.data) } } function postParamsType(params, postType) { //post 數據類型設置 if (postType == 'none') { return params; } else if (postType == 'formdata') { return objToFormData({ data: params, arrayKey: false }); } else { return qs.stringify(params, { arrayFormat: 'brackets' }); } }

 

 

以上是本人在項目中使用的ajax部分的代碼,在vue項目中能有比較好的性能和使用,能夠實現緩存和對重複加載的阻止。vue

 

具體使用方法,大概是就是調用apiLink這個主要方法實現ajax請求,配置參數能夠實現想實現和不想實現的功能,好比開啓緩存就多加saved參數。ios

===POST使用事例:ajax

apiLink({
        routelink: utypes.GET_PARTY_SPEAK_ADD, 
        params: { mid: params, content: pubSpeakContent },
        method: 'post',
        callback: (res) => {
            console.log(res)
        }
    })

以上代碼就是一個post的使用事例,你們能夠參考。vuex

===GET使用事例:axios

apiLink({
        routelink: utypes.GET_PARTY_MEET_SEARCH,
        params: { mid: params, name: searchConfig.name, content: searchConfig.content },
        callback: (res) => {
            commit(mtypes.SET_PARTY_MEET_SEARCH, res)
        }
    })

以上代碼就是一個get的使用事例,你們能夠參考。api

 

===使用參數說明:緩存

apiLink({
        routelink: /url, //api地址
        params: {}, //參數傳遞
        saved:true,true表明開啓緩存,讀取緩存功能,非必傳,不傳默認不讀取緩存
        method:'post',//post或get方法設置,非必傳,不傳默認get
postType:'formdata', //非必傳,不傳默認qs格式化
callback: (res) => { //回調 }, error:err=>{} //錯誤回調,非必傳 })

 

===對象轉formdata格式代碼:app

 

export function objToFormData(config) { //對象轉formdata格式
    let formData = new FormData();
    let obj = config.data;
    let arrayKey = config.arrayKey;
    for (var i in obj) {
        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])
        }
    }
    return formData;
}

上面這個方法能夠方便的實現obj對象轉formdata格式。post

===結論:性能

代碼實踐過,以爲挺好用,分享出來,你們參考參考,具體須要本身改進下才能適合你的項目。

相關文章
相關標籤/搜索