Vue基於Axios網絡請求封裝

結構
api.js 將所有的接口統一管理
request.js 對網絡請求進行了封裝操作
image.png
封裝代碼
api.js

//api地址
const HOST = "http://xxx.com";
const API = HOST + "/api/public/";

const Apis = {
    // 產品
    getProduct: API + 'product',
    // 微信購買
    wxPay: API + 'weixinPay',
}
export default Apis

request.js

import Apis from "./api";
import axios from 'axios'
import {Message} from 'element-ui';

const METHOD = {
    GET: 'get',
    POST: 'post'
}
/**
 * 網絡請求
 * @param method 方法
 * @param url 接口地址
 * @param params 參數
 * @param showError 是否展示錯誤信息
 * @returns {Promise<any>}
 */
// 錯誤和失敗信息都在這裏進行處理,界面中調用的時候只處理正確數據即可
function request(method, url, params, showError) {
    if (showError || showError == undefined){ // 是否展示錯誤信息
        showError = true;
    }else {
        showError = false;
    }
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            url: url,
            params: params
        }).then((res) => {
            if (res.data.code == 0) { // 0 是請求成功
                resolve(res.data.data);
            } else { // 其他情況返回錯誤信息,根據需要處理
                reject(res.data);
                if (showError){
                    Message.error(res.data.message);
                }
            }
        }).catch(() => {
            if (showError){
                Message.error('請求失敗,請稍後再試');
            }
        });
    });
}

/**
 * 圖片上傳
 * @param url 地址
 * @param params 參數 FormData
 * @param showError 是否展示錯誤
 * @returns {Promise<any>}
 */
function uploadRequest(url, params, showError) {
    if (showError || showError == undefined){
        showError = true;
    }else {
        showError = false;
    }
    let config = {
        headers: { "Content-Type": "multipart/form-data" },
    }
    return new Promise((resolve, reject) => {
        axios.post(url,params,config).then((res) => {
            if (res.data.code == 0) {
                resolve(res.data.data);
            } else {
                reject(res.data);
                if (showError){
                    Message({
                        type: 'error',
                        message: res.data.message,
                        duration: 1000
                    });
                }
            }
        }).catch(() => {
            if (showError){
                Message({
                    type: 'error',
                    message: '請求失敗,請稍後再試',
                    duration: 1000
                });
            }
        });
    });
}

function get(url, params, showError) {
    return request(METHOD.GET, url, params, showError);
}

function post(url, params, showError) {
    return request(METHOD.POST, url, params, showError);
}

function upload(url, params, showError) {
    return uploadRequest(url, params, showError);
}
const API = {
    // 產品
    getProduct: (params) => post(Apis.getProduct, params),
    // 微信購買
    wxPay: (params) => post(Apis.wxPay, params),
}

function install(Vue) {
    Vue.prototype.$request = API;
}
export default install

具體使用
main.js 引入

import VueRequest from './js/vuex/request'
Vue.use(VueRequest);

xxx.vue界面使用

<script>
    export default {
        name: "xxx",
        data() {
            return {
                tableData: []
            }
        },
        mounted() {
            this.loadModuleData();
        },
        methods: {
            /**
             * 產品數據獲取
             */
            loadProductData() {
                let params = {
                    uid: xxx
                }
                this.$request.getProduct(
                    params
                ).then((data)=>{ // 直接拿到的就是成功數據,其他情況封裝的時候統一處理
                    data.forEach(data => {
                        this.tableData.push({
                            id: data.id || '',
                            name: data.name || '',
                            desc: data.desc || '',
                        })
                    })
                });
            },
           // 文件上傳
          uploadFile(file){
                let params = new FormData();
                params.append('file', file);
                params.append('ucenter_id', this.$store.getUserId());
                this.$request.uploadImage(
                    uploadData
                ).then((res) => {
                    console.log(res);
                });
            }
        }
    }
</script>

Axios 易用、簡潔且高效的http庫
Promise詳解
Element一套爲開發者、設計師和產品經理準備的基於Vue的桌面端組件庫

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章