uni-app網(wǎng)絡(luò)請求封裝

1. 普通網(wǎng)絡(luò)請求

1.1 未封裝前index.vue頁面使用

getMachineNum:function(){
    var timestamp = Date.parse(new Date());//時(shí)間戳
    var token = uni.getStorageSync(_self.sessionKey);
    var device = "wxapp";
    var ver = "1.1.30";
            
    uni.request({
        url: this.siteBaseUrl + 'machine/index',
        method: 'GET',
        data: {
            token : token,
            timestamp : timestamp,
            device : device,
            ver : ver
        },
        success: res => {
            console.log("getMachineNum success:" + JSON.stringify(res));
            if (res.data.code == "-1") {//登錄失效
                uni.showToast({
                    title: res.data.msg,
                    mask: false,
                    duration: 1500
                });
            } else if (res.data.code == "0") {
                var data = res.data.data;
                _self.onlineNum = data.onlineNum;
                _self.machineNum = data.machineNum;
            }else {
                console.log("未處理的結(jié)果碼");
            }
                    
        },
        fail: (e) => {
            console.log("getMachineNum fail:" + JSON.stringify(e));
        },
        complete: () => {}
    });
},

請求結(jié)果

{
  "data": {
    "code": "0",
    "msg": "success",
    "data": {
      "machineNum": 124,
      "onlineNum": 1,
      
    }
  },
  "header": {
    "Server": "nginx/1.14.0",
    "Date": "Thu, 11 Apr 2019 03:08:20 GMT",
    "Content-Type": "application/json;charset=utf-8;",
    "Transfer-Encoding": "chunked",
    "Connection": "keep-alive",
    "X-Powered-By": "PHP/7.1.16"
  },
  "statusCode": 200,
  "cookies": [],
  "errMsg": "request:ok"
}

1.2 main.js中封裝網(wǎng)絡(luò)請求

  • main.js
Vue.prototype.sendRequest= function(param,backpage, backtype){
    var _self = this, 
        url = param.url,
        data = param.data || {}, 
        header = param.header,
        token = "";
        
    //拼接完整請求地址
    var requestUrl = this.siteBaseUrl + url;
    //固定參數(shù)
    if(!data.token){//如果參數(shù)中無token(除了小程序第一次通過code獲取token的接口默認(rèn)參數(shù)token = login,其他接口token參數(shù)都是在本地緩存中獲取)
        token = uni.getStorageSync(this.sessionKey);
        if(!token){//本地?zé)otoken需重新登錄
            _self.login(backpage, backtype);
            return;
        }else{
            data.token = token;
        }
    }
    var timestamp = Date.parse(new Date());//時(shí)間戳
    data["timestamp"] = timestamp;
    data["device"] = "wxapp";//data["device"] = "iosapp";
    data["ver"] = "1.1.30";//data["ver"] = "1.0.0";
    
    //GET或POST
    if(param.method){
        param.method = param.method.toUpperCase();//小寫改為大寫
    }
    
    //網(wǎng)絡(luò)請求
    uni.request({
        url: requestUrl,
        method: param.method || "GET",
        header: header || {'content-type' : "application/json"},
        data: data,
        success: res => {
            console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
            if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤
                uni.showModal({
                    content:"" + res.errMsg
                });
                return;
            }
            if (res.data.code) {//返回結(jié)果碼code判斷:0成功,1錯(cuò)誤,-1未登錄
                if (res.data.code == "-1") {
                    _self.login(backpage, backtype);
                    return;
                }
                if (res.data.code != "0") {
                    uni.showModal({
                        showCancel:false,
                        content:"" + res.data.msg
                    });
                    return;
                }
            } else{
                uni.showModal({
                    showCancel:false,
                    content:"" + res.data.msg
                });
                return;
            }
            
            typeof param.success == "function" && param.success(res.data);
        },
        fail: (e) => {
            console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
            uni.showModal({
                content:"" + res.errMsg
            });
            
            typeof param.fail == "function" && param.fail(res.data);
        },
        complete: () => {
            console.log("網(wǎng)絡(luò)請求complete");
            uni.hideLoading();
            
            typeof param.complete == "function" && param.complete(res.data);
            return;
        }
    });
}

Vue.prototype.login = function(backpage, backtype){
    var _self = this;
    uni.login({
        success:function(res){
            _self.requestData({
                url : "user/login",
                data : {
                    code : res.code, 
                    token : "login"
                },
                success : function(res2){
                    if (res2.data.errCode == "0") {//用戶存在:存儲(chǔ)token
                        uni.setStorageSync(_self.sessionKey,res2.data.token);
                    } else if (res2.data.errCode == "0") {//用戶不存在:調(diào)轉(zhuǎn)到綁定頁面
                        uni.redirectTo({url:'../binding/binding?backpage='+backpage+'&backtype='+backtype});
                        return false;
                    }
                }
            },backpage, backtype)
        },
        fail:function(e){
            console.log("微信login接口調(diào)用失敗:" + JSON.stringify(e));
        }
    });
    return;
}


Vue.prototype.siteBaseUrl = 'https://api.uchat.com.cn/';

Vue.prototype.sessionKey = "sess_jk";
  • 封裝后index.vue頁面get請求調(diào)用
getMachineNum:function(){
    this.sendRequest({
        url : "machine/index",
        success : function(res){
            console.log("getMachineNum success:" + JSON.stringify(res));
            var data = res.data;
            _self.onlineNum = data.onlineNum || 0;
            _self.machineNum = data.machineNum || 0;
        },
        fail:function(e){
            console.log("getMachineNum  fail:" + JSON.stringify(e));
        }
    },'../myhome/myhome','2')
}

注意:頁面POST請求header需配置為 {'content-type' : "application/x-www-form-urlencoded"}币呵,如:

initData:function () {
    this.sendRequest({
        url : "CompanyTeam/teamInfo",
        data : {ct_id : ct_id},
        method : "POST",
        header: {'content-type' : "application/x-www-form-urlencoded"},
        success:function (res) {
            console.log("獲取數(shù)據(jù):" + JSON.stringify(res));
        }
    },"/pages/machineGroupOutput/machineGroupOutput","1")
},

故禾嫉,可對網(wǎng)絡(luò)請求封裝繼續(xù)優(yōu)化始腾。

1.3 網(wǎng)絡(luò)請求封裝優(yōu)化

  • main.js
Vue.prototype.sendRequest = function(param,backpage, backtype){
    var _self = this, 
        url = param.url,
        method = param.method,
        header = {},
        data = param.data || {}, 
        token = "",
        hideLoading = param.hideLoading || false;
        
    //拼接完整請求地址
    var requestUrl = this.siteBaseUrl + url;
    //固定參數(shù):僅僅在小程序綁定頁面通過code獲取token的接口默認(rèn)傳遞了參數(shù)token = login
    if(!data.token){//其他業(yè)務(wù)接口傳遞過來的參數(shù)中無token
        token = uni.getStorageSync(this.sessionKey);//參數(shù)中無token時(shí)在本地緩存中獲取
        console.log("當(dāng)前token:" + token);
        if(!token){//本地?zé)otoken需重新登錄(退出時(shí)清緩存token)
            _self.login(backpage, backtype);
            return;
        }else{
            data.token = token;
        }
    }
    var timestamp = Date.parse(new Date());//時(shí)間戳
    data["timestamp"] = timestamp;
    // #ifdef MP-WEIXIN
    data["device"] = "wxapp";
    data["ver"] = "1.1.30";
    // #endif
    // #ifdef APP-PLUS || H5
    data["device"] = "iosapp";
    data["ver"] = "1.0.0";
    // #endif
    
    //請求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
    if(method){
        method = method.toUpperCase();//小寫改為大寫
        if(method=="POST"){
            header = {'content-type' : "application/x-www-form-urlencoded"};
        }else{
            header = {'content-type' : "application/json"};
        }
    }else{
        method = "GET";
        header = {'content-type' : "application/json"};
    }
    //用戶交互:加載圈
    if (!hideLoading) {
        uni.showLoading({title:'加載中...'});
    }
    
    console.log("網(wǎng)絡(luò)請求start");
    //網(wǎng)絡(luò)請求
    uni.request({
        url: requestUrl,
        method: method,
        header: header,
        data: data,
        success: res => {
            console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
            if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤
                uni.showModal({
                    content:"" + res.errMsg
                });
                return;
            }
            if (res.data.code) {//返回結(jié)果碼code判斷:0成功,1錯(cuò)誤,-1未登錄(未綁定/失效/被解綁)
                if (res.data.code == "-1") {
                    _self.login(backpage, backtype);
                    return;
                }
                if (res.data.code != "0") {
                    uni.showModal({
                        showCancel:false,
                        content:"" + res.data.msg
                    });
                    return;
                }
            } else{
                uni.showModal({
                    showCancel:false,
                    content:"No ResultCode:" + res.data.msg
                });
                return;
            }
            typeof param.success == "function" && param.success(res.data);
        },
        fail: (e) => {
            console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
            uni.showModal({
                content:"" + e.errMsg
            });
            typeof param.fail == "function" && param.fail(e.data);
        },
        complete: () => {
            console.log("網(wǎng)絡(luò)請求complete");
            if (!hideLoading) {
                uni.hideLoading();
            }
            typeof param.complete == "function" && param.complete();
            return;
        }
    });
}

  • 頁面POST請求調(diào)用
initData:function () {
    this.sendRequest({
        url : "CompanyTeam/teamInfo",
        method : "POST",
        data : {ct_id : ct_id},
        hideLoading : true,
        success:function (res) {
            console.log("獲取數(shù)據(jù):" + JSON.stringify(res));
        }
    },"/pages/machineGroupOutput/machineGroupOutput","1")
},

拓展:設(shè)置網(wǎng)絡(luò)請求為同步可參考Promise 封裝。大致可分為三種方案:請求嵌套(異步方式的成功回調(diào)里獲取數(shù)據(jù)后再采用異步方式請求)咬扇、promise 或者await,具體實(shí)現(xiàn)可自行實(shí)踐赔退,這里不詳細(xì)敘述忌堂。

2. 文件上傳封裝

(1) 未封裝前index.vue頁面使用

commitUnqualifiedInfoAndFile:function(filePath){
    uni.uploadFile({
        url: 'http://' + _self.getIP() + '/' + 'ticket/toCheck', 
        filePath: filePath,
        name: 'image',
        formData: {
            token : uni.getStorageSync(this.sessionKey),
            timestamp : Date.parse(new Date()),
            style_id : "7",
            production_id : "SCD778",
            qualified_num:0
        },
        success: (res) => {
            console.log("res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
            console.log("statusCode:" + res.statusCode);
            console.log("uniapp上傳文件api返回的data是字符串類型:"+ res.data);
            var dataString = res.data;//json字符串
            var res = JSON.parse(dataString);//json字符串轉(zhuǎn)json對象

            console.log("code:"+ res.code);
            console.log("msg:"+ res.msg);
            uni.showToast({
                title:res.data.msg ? res.data.msg : "成功",
                icon:'none'
            }); 
            console.log("data_1:"+ res.data.qualified_num);
            console.log("data_2:"+ res.data.failed_num);
        },
        fail: (e) => {
            console.log("網(wǎng)絡(luò)請求fail");
        },
        complete: () => {
            console.log("網(wǎng)絡(luò)請求complete");
        }
    });
},

備注:后臺返回的data值如下

{
  "data": {
    "msg": "質(zhì)檢完成",
    "qualified_num": 41,
    "failed_num": "17"
  },
  "code": "0",
  "msg": "success"
}

打印結(jié)果:uniapp上傳文件api返回的data是字符串類型,需先將data轉(zhuǎn)換為json對象拴曲,之后再取里面的值挣郭。

打印結(jié)果.png

(2) main.js中封裝網(wǎng)絡(luò)請求

//上傳文件
Vue.prototype.uploadFileRequest = function(param){
    var _self = this, 
        url = param.url || "",
        path = param.path || "",
        name = param.name || "file",
        data = param.data || {},
        token = "";
        
    if(url == ""){
        url =  _self.getUploadFileUrl();//默認(rèn)的上傳文件地址
    }else{
        url = "http://" + this.getIP() + "/" + url;
    }
    
    if(!data.token){
        token = uni.getStorageSync(this.sessionKey);
        console.log("當(dāng)前token:" + token);
        if(!token){
            uni.redirectTo({url:'/pages/login1/login1'});
            return;
        }else{
            data.token = token;
        }
    }
    var timestamp = Date.parse(new Date());//時(shí)間戳
    data["timestamp"] = timestamp;
    
    console.log("網(wǎng)絡(luò)請求start:url:" + url + ",params:" +JSON.stringify(data));
    uni.uploadFile({ 
        url: url, 
        filePath: path,
        name: name,
        formData: data,
        success: (res) => {
            console.log("網(wǎng)絡(luò)請求success-res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
            console.log("網(wǎng)絡(luò)請求success-statusCode:" + res.statusCode);
            console.log("uniapp上傳文件api返回的data是字符串類型:" + res.data);
            if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤(Error StatusCode)
                uni.showToast({
                    /* title:res.errMsg */
                    title:"api錯(cuò)誤",
                    icon:'none'
                });
                
                return;
            }
            var dataString = res.data;//json字符串
            var res = JSON.parse(dataString);//json字符串轉(zhuǎn)json對象
            if (res.code) {
                if (res.code != "0") {//Error ResultCode
                    uni.showToast({
                        title:res.msg,
                        icon:'none'
                    });
                    
                    return;
                }
            } else {//No ResultCode
                uni.showToast({
                    /* title:res.msg */
                    title:"無結(jié)果碼",
                    icon:'none'
                });
                
                return;
            }
            typeof param.success == "function" && param.success(res);
        },
        fail: (e) => {
            console.log("網(wǎng)絡(luò)請求fail");
            uni.showToast({
                /* title: e.errMsg */
                title:"請檢查網(wǎng)絡(luò)",
                icon:'none'
            });
            typeof param.fail == "function" && param.fail(e.data);
        },
        complete: () => {
            console.log("網(wǎng)絡(luò)請求complete");
            typeof param.complete == "function" && param.complete();
            return;
        }
    });
}

(3) 封裝后index.vue頁面調(diào)用

commitUnqualifiedInfoAndFile:function(filePath){
    _self.uploadFileRequest({
        url:'ticket/toCheck',
        path: filePath,
        name: 'image',
        data:{
            style_id : "7",
            production_id : "SCD778",
            qualified_num:0,
        },
        success: (res) => {
            console.log("res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
            uni.showToast({
                title:res.data.msg ? res.data.msg : "成功",
                icon:'none'
            }); 
        },
        fail: (e) => {
            
        },
        complete: () => {
            
        }
    });

},

3. 所有網(wǎng)絡(luò)請求封裝為公用js文件

(1) http.js

const baseUrl = "http://api.liy.cn"

//網(wǎng)絡(luò)判斷
const hasNetwork = function(){
    var result = true;
    uni.getNetworkType({
        success: function (res) {
            console.log("網(wǎng)絡(luò)類型:" + res.networkType);
            if(res.networkType == "none"){
                uni.showToast({
                    title:"網(wǎng)絡(luò)未連接",
                    icon:'none'
                });
                result = false;
            }
        }
    });
    return result;
}

//登錄請求
const sendLoginRequest = function(param){
    //為什么程序未執(zhí)行網(wǎng)絡(luò)變化的監(jiān)聽:網(wǎng)絡(luò)發(fā)生變化才會(huì)觸發(fā)
    // uni.onNetworkStatusChange(function(res){
    //  // console.log("網(wǎng)絡(luò)類型:" + res.networkType + ",網(wǎng)絡(luò)連接:" + res.isConnected);
    //  if(!res.isConnected){
    //      uni.showToast({
    //          title:"網(wǎng)絡(luò)未連接",
    //          icon:'none'
    //      });
    //      return;
    //  }
    // })
    
    // if(!hasNetwork()){//移到頁面中判斷:適配按鈕狀態(tài)變化的邏輯
    //  return;
    // }

    var _self = this, data = param.data || {}, siteBaseUrl = baseUrl + "/";
    uni.request({
        url: siteBaseUrl + "user/login",
        method: 'POST',
        //header: {'content-type' : "application/json"},//默認(rèn)
        header: {'content-type' : "application/x-www-form-urlencoded"},
        data: data,
        success:function(res){
            console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
            if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤(Error StatusCode)
                uni.showToast({
                    /* title:res.errMsg */
                    title:"api錯(cuò)誤",
                    icon:'none'
                });
                
                return;
            }
            if (res.data.code) {
                if (res.data.code != "0") {//Error ResultCode
                    uni.showToast({
                        title:res.data.msg,
                        icon:'none'
                    });
                    
                    return;
                }
            } else {//No ResultCode
                uni.showToast({
                    /* title:res.data.msg */
                    title:"無結(jié)果碼",
                    icon:'none'
                });
                
                return;
            }
            typeof param.success == "function" && param.success(res.data);
        },
        fail:function(e){
            console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
            uni.showToast({
                /* title:e.errMsg */
                title:"請檢查網(wǎng)絡(luò)",
                icon:'none'
            });
            
            typeof param.fail == "function" && param.fail(e.data);
        },
        complete:function(){
            console.log("網(wǎng)絡(luò)請求complete");
            typeof param.complete == "function" && param.complete();
            return;
        }
    });
}

//封裝除登錄外的業(yè)務(wù)網(wǎng)絡(luò)請求
const sendRequest = function(param){
    if(!hasNetwork()){//移到頁面中判斷:適配按鈕狀態(tài)變化的邏輯
        return;
    }
    var _self = this, 
        url = param.url,
        method = param.method,
        header = {},
        data = param.data || {}, 
        token = "",
        hideLoading = param.hideLoading || true;
        
    //拼接完整請求地址
    var requestUrl = baseUrl + "/" + url;
    //固定參數(shù):僅僅在小程序綁定頁面通過code獲取token的接口默認(rèn)傳遞了參數(shù)token = login
    if(!data.token){//其他業(yè)務(wù)接口傳遞過來的參數(shù)中無token
        token = uni.getStorageSync(this.sessionKey);//參數(shù)中無token時(shí)在本地緩存中獲取
        console.log("當(dāng)前token:" + token);
        if(!token){//本地?zé)otoken需重新登錄(退出時(shí)清緩存token)
            uni.redirectTo({url:'/pages/login/login'});
            return;
        }else{
            data.token = token;
        }
    }
    var timestamp = Date.parse(new Date());//時(shí)間戳
    data["timestamp"] = timestamp;
    var center_id = _self.getUserInfo().center_id || "";
    data["center_id"] = center_id;
    
    //請求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
    if(method){
        method = method.toUpperCase();//小寫改為大寫
        if(method=="POST"){
            header = {'content-type' : "application/x-www-form-urlencoded"};
        }else{
            header = {'content-type' : "application/json"};
        }
    }else{
        method = "GET";
        header = {'content-type' : "application/json"};
    }
    //用戶交互:加載圈
    if (!hideLoading) {
        uni.showLoading({title:'加載中...'});
    }
    
    console.log("網(wǎng)絡(luò)請求start:url:" + requestUrl + "疗韵,params:" +JSON.stringify(data));
    //網(wǎng)絡(luò)請求
    uni.request({
        url: requestUrl,
        method: method,
        header: header,
        data: data,
        success: res => {
            console.log("網(wǎng)絡(luò)請求success:" + JSON.stringify(res));
            if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤
                uni.showToast({
                    /* title: res.errMsg */
                    title:"api錯(cuò)誤",
                    icon:'none'
                });
                return;
            }
            if (res.data.code) {//返回結(jié)果碼code判斷:0成功,1錯(cuò)誤,-1未登錄(未綁定/失效/被解綁)
                if (res.data.code == "-1") {
                    uni.redirectTo({url:'/pages/login2/login2'});
                    return;
                }
                if (res.data.code != "0") {//code為1失敗,code為0成功
                    uni.showToast({
                        title: res.data.msg,
                        icon:'none'
                    });
                    return;
                }
            } else{
                uni.showToast({
                    /* title: res.data.msg */
                    title:"無結(jié)果碼",
                    icon:'none'
                });
                return;
            }
            typeof param.success == "function" && param.success(res.data);
        },
        fail: (e) => {
            console.log("網(wǎng)絡(luò)請求fail:" + JSON.stringify(e));
            uni.showToast({
                /* title: e.errMsg */
                title:"請檢查網(wǎng)絡(luò)",
                icon:'none'
            });
            
            typeof param.fail == "function" && param.fail(e.data);
        },
        complete: () => {
            console.log("網(wǎng)絡(luò)請求complete");
            if (!hideLoading) {
                uni.hideLoading();
            }
            typeof param.complete == "function" && param.complete();
            return;
        }
    });
}

//上傳文件
const uploadFileRequest = function(param){
    if(!hasNetwork()){//移到頁面中判斷:適配按鈕狀態(tài)變化的邏輯
        return;
    }
    var _self = this, 
        url = param.url || "",
        path = param.path || "",
        name = param.name || "file",
        data = param.data || {},
        token = "";
        
    if(url == ""){
        url =  _self.getUploadFileUrl();//默認(rèn)的上傳文件地址
    }else{
        url = baseUrl + "/" + url;
    }
    
    if(!data.token){
        token = uni.getStorageSync(this.sessionKey);
        console.log("當(dāng)前token:" + token);
        if(!token){
            uni.redirectTo({url:'/pages/login2/login2'});
            return;
        }else{
            data.token = token;
        }
    }
    var timestamp = Date.parse(new Date());//時(shí)間戳
    data["timestamp"] = timestamp;
    
    console.log("網(wǎng)絡(luò)請求start:url:" + url + "侄非,params:" +JSON.stringify(data));
    uni.uploadFile({ 
        url: url, 
        filePath: path,
        name: name,
        formData: data,
        success: (res) => {
            console.log("網(wǎng)絡(luò)請求success-res:" + JSON.stringify(res));//json對象轉(zhuǎn)json字符串
            console.log("網(wǎng)絡(luò)請求success-statusCode:" + res.statusCode);
            console.log("uniapp上傳文件api返回的data是字符串類型:" + res.data);
            if (res.statusCode && res.statusCode != 200) {//api錯(cuò)誤(Error StatusCode)
                uni.showToast({
                    /* title:res.errMsg */
                    title:"api錯(cuò)誤",
                    icon:'none'
                });
                
                return;
            }
            var dataString = res.data;//json字符串
            var res = JSON.parse(dataString);//json字符串轉(zhuǎn)json對象
            if (res.code) {
                if (res.code != "0") {//Error ResultCode
                    uni.showToast({
                        title:res.msg,
                        icon:'none'
                    });
                    
                    return;
                }
            } else {//No ResultCode
                uni.showToast({
                    /* title:res.msg */
                    title:"無結(jié)果碼",
                    icon:'none'
                });
                
                return;
            }
            typeof param.success == "function" && param.success(res);
        },
        fail: (e) => {
            console.log("網(wǎng)絡(luò)請求fail");
            uni.showToast({
                /* title: e.errMsg */
                title:"請檢查網(wǎng)絡(luò)",
                icon:'none'
            });
            typeof param.fail == "function" && param.fail(e.data);
        },
        complete: () => {
            console.log("網(wǎng)絡(luò)請求complete");
            typeof param.complete == "function" && param.complete();
            return;
        }
    });
}

export default {
    sendLoginRequest,
    sendRequest,
    uploadFileRequest
}

(2) 單頁面引入js文件并調(diào)用

<script>
import Http from '../../common/http.js'
var _self;
export default {
    data() {
        return {
            logining: false
        }
    },
    methods: {
        login:function(){
            _self = this;
            if(!this.Http.hasNetwork()){
                return;
            }
            _self.logining = true;//按鈕不可用
            Http.sendLoginRequest({
                data: {
                    mobile : "15639150623",
                    password : "aaaaaa"
                },
                success:function(res){
                    uni.switchTab({
                        url:'../tabBar/home/home'
                    })
                },
                fail:function(e){},
                complete:function(){
                    _self.logining = false;//按鈕可用
                }
            })
        }
    }
}
</script>

(3) 全局引入js文件并調(diào)用

  • main.js
import Vue from 'vue'
import App from './App'

import Http from './common/http.js'

Vue.config.productionTip = false
Vue.prototype.Http = Http 


App.mpType = 'app'

const app = new Vue({
    Http,
    ...App
})
app.$mount()

  • 頁面調(diào)用
<script>
// import Http from '../../common/http.js'
var _self;
export default {
    data() {
        return {
            logining: false
        }
    },
    methods: {
        login:function(){
            _self = this;
            if(!this.Http.hasNetwork()){
                return;
            }
            _self.logining = true;//按鈕不可用
            this.Http.sendLoginRequest({
                data: {
                    mobile : "15639150623",
                    password : "aaaaaa"
                },
                success:function(res){
                    uni.switchTab({
                        url:'../tabBar/home/home'
                    })
                },
                fail:function(e){},
                complete:function(){
                    _self.logining = false;//按鈕可用
                }
            })
        }
    }
}
</script>

說明:目前已發(fā)布到uniapp插件市場蕉汪,有需要請移步網(wǎng)絡(luò)請求封裝流译。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市者疤,隨后出現(xiàn)的幾起案子福澡,更是在濱河造成了極大的恐慌,老刑警劉巖驹马,帶你破解...
    沈念sama閱讀 211,290評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件革砸,死亡現(xiàn)場離奇詭異,居然都是意外死亡糯累,警方通過查閱死者的電腦和手機(jī)算利,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,107評論 2 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泳姐,“玉大人效拭,你說我怎么就攤上這事∨置耄” “怎么了缎患?”我有些...
    開封第一講書人閱讀 156,872評論 0 347
  • 文/不壞的土叔 我叫張陵,是天一觀的道長阎肝。 經(jīng)常有香客問我挤渔,道長,這世上最難降的妖魔是什么风题? 我笑而不...
    開封第一講書人閱讀 56,415評論 1 283
  • 正文 為了忘掉前任判导,我火速辦了婚禮,結(jié)果婚禮上俯邓,老公的妹妹穿的比我還像新娘骡楼。我一直安慰自己,他們只是感情好稽鞭,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,453評論 6 385
  • 文/花漫 我一把揭開白布鸟整。 她就那樣靜靜地躺著,像睡著了一般朦蕴。 火紅的嫁衣襯著肌膚如雪篮条。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,784評論 1 290
  • 那天吩抓,我揣著相機(jī)與錄音涉茧,去河邊找鬼。 笑死疹娶,一個(gè)胖子當(dāng)著我的面吹牛伴栓,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 38,927評論 3 406
  • 文/蒼蘭香墨 我猛地睜開眼钳垮,長吁一口氣:“原來是場噩夢啊……” “哼惑淳!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起饺窿,我...
    開封第一講書人閱讀 37,691評論 0 266
  • 序言:老撾萬榮一對情侶失蹤歧焦,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后肚医,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體绢馍,經(jīng)...
    沈念sama閱讀 44,137評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,472評論 2 326
  • 正文 我和宋清朗相戀三年肠套,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了舰涌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,622評論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡糠排,死狀恐怖舵稠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情入宦,我是刑警寧澤哺徊,帶...
    沈念sama閱讀 34,289評論 4 329
  • 正文 年R本政府宣布,位于F島的核電站乾闰,受9級特大地震影響落追,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜涯肩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,887評論 3 312
  • 文/蒙蒙 一轿钠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧病苗,春花似錦疗垛、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,741評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至咬展,卻和暖如春泽裳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背破婆。 一陣腳步聲響...
    開封第一講書人閱讀 31,977評論 1 265
  • 我被黑心中介騙來泰國打工涮总, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人祷舀。 一個(gè)月前我還...
    沈念sama閱讀 46,316評論 2 360
  • 正文 我出身青樓瀑梗,卻偏偏與公主長得像烹笔,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子夺克,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,490評論 2 348

推薦閱讀更多精彩內(nèi)容