封装统一请求函数有利于项目的维护
整体功能简单实用,但小编遇到一个巨坑,项目中在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:"提示",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;
原文地址:https://www.cnblogs.com/zmdComeOn
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。