封裝統一請求函數有利於項目的維護
整體功能簡單實用,但小編遇到一個巨坑,項目中在vue文件使用跳轉方法,url參數輸入 "/" 后工具提示的路徑為 "/pages/login/login",
但是在外部js文件中使用uni跳轉的api,快捷提示的路徑為 "/pages/login/login.vue" , 這就導致實際使用找不到了,類似的情況要注意一下。
參考如下:在common文件夾下面建立一個util.js,內容如下
import {getHttpUrl} from "common/server.js" const domain = getHttpUrl() + "/api/instructor.php/" const req = function(a){ //console.log(a.url);
a = a || {}; var b = { url: domain + (a.url || ""), method: a.method || "POST", dataType: a.dataType || "json", header: a.header || {}, data: a.data || {}, timeout: a.timeout || 30000, success: a.success || undefined, fail: a.fail || undefined, complete: a.complete || undefined, toLogin:a.toLogin || "no" }; if(a.loading){ uni.showLoading({ title:a.loadingTitle || "加載中", mask: a.loadingMask || true }) } uni.request({ url:b.url, method:b.method, data:b.data, header:b.header, dataType:b.dataType, timeout:b.timeout, success:function(res){ if(res.statusCode != 200){ uni.showModal({ title:"提示", content:"服務器繁忙,請稍后再試", confirmColor:"#009714", showCancel:false }) return; } //console.log(res);
if(res.data.code == 0){ //console.log(res.data);
if(b.success){ b.success(res) } }else{ if(res.data.code == "-1" && res.data.msg == "未登錄"){ if(b.toLogin == "yes"){ setTimeout(function(){ uni.redirectTo({ url:"/pages/login/login" }) },1000) }else{ try{ uni.removeStorageSync("userInfo"); }catch(e){ //TODO handle the exception
} uni.showModal({ title:"提示", content:"您未登錄,請登錄后再試", showCancel:false, confirmText:"去登陸", confirmColor:"#FF0000", success(e) { if(e.confirm){ uni.redirectTo({ url:"/pages/login/login" }) } } }) } return; } var tipMsg = res.data.msg ? res.data.msg : "暫無數據"; setTimeout(function(){ uni.showToast({ title:tipMsg, icon:"none", mask:true, duration:1500 }) },200) } },fail:function(err){ if(b.fail){ b.fail(err); }else{ uni.showModal({ title:"提示", content:"服務器繁忙,請稍后再試", confirmColor:"#009714", showCancel:false }) } },complete:function(com){ //關閉加載提示
if(a.loading){ uni.hideLoading(); } if(b.complete){ b.complete(com); } } }) } module.exports = { req:req }
使用方法:
1、在要使用的vue頁面中引入
2、注冊到全局vue方法
import util from 'common/util.js'
//統一接口請求函數
Vue.prototype.req = util.req;