const REQUESTURL = "http://192.168.2.164:8888"; //请求路径
// 短文字提示框
const LOADING = function(msg) {
uni.showLoading({
title: msg, // 除支付宝最多显示7个汉字长度
icon: "none"
})
};
// 请求参数拦截器
const REQUESTOPTIONSINTERCEPT = function(options) {
return options;
};
// 服务器应答数据拦截器
const REQUESTSUCCESSINTERCEPT = function(res) {
res = res.data;
if (res.code != 0) throw res.msg;
return res;
};
// 传递给global的参数
const GLOBALOPTIONS = {
REQUESTURL
};
// 将暴露在整个项目的全局自定义类
class global {
constructor(options) {
this.options = options;
this.loading = LOADING;
this.systemInfo = getSystemInfo();
this.prev = Date.now(); //节流使用
}
// 获取二维码参数 options.scene
qrcodeValue(scene){
scene=decodeURIComponent(scene).split("&");
scene = scene.map(item => (item.split("=")));
return Object.fromEntries(scene);
}
// 富文本处理
richTextChange(value){
/**
* 此代码段处理目的为,匹配富文本代码中的
标签,并将其图片的宽度修改为适应屏幕
* max-width:100% --- 图片宽度加以限制,避免超出屏幕
* height:auto --- 高度自适应
* display:block --- 此代码,可以去掉图片之间的空白间隔,个人觉得好用
*/
value = value.replace(/
len) return string;
for (let i = 0; i < len - string.length; i++) {
string = '0' + string;
}
return string;
}
// 防抖
debounce(func, wait = 1000) {
if (typeof func !== 'function') {
throw new TypeError('need a function arguments')
}
let timeid = null;
let result;
return function() {
let context = this;
let args = arguments;
if (timeid) {
clearTimeout(timeid);
}
timeid = setTimeout(function() {
result = func.apply(context, args);
}, wait);
return result;
}
}
// 节流
throttle(func, delay = 1000) {
let that = this;
return function() {
var context = this;
var args = arguments;
var now = Date.now();
if (now - that.prev >= delay) {
console.log("执行")
func.apply(context, args);
that.prev = Date.now();
}
}
}
// 请求
request(options) {
options.url = this.options.REQUESTURL + options.url;
options = REQUESTOPTIONSINTERCEPT(options);
// 根据参数判断loading的形态
if (options.loading) {
uni.showLoading(showLoadingValueTypeOf(options.loading) ? {
title: options.loading
} : {});
}
return new Promise((resolve, reject) => {
uni.request({
...options,
success(res) {
try {
res = REQUESTSUCCESSINTERCEPT(res)
resolve(res);
} catch (err) {
reject(err)
}
},
fail(err) {
reject(err);
},
complete() {
options.complete && options.complete();
if (options.loading) uni.hideLoading();
}
})
})
}
}
function showLoadingValueTypeOf(value) {
return typeof(value) == 'string';
}
// 系统数据
function getSystemInfo() {
const options = {};
uni.getSystemInfo({
success: res => {
options.StatusBar = res.statusBarHeight;
var capsule = wx.getMenuButtonBoundingClientRect();
if (capsule) {
options.Custom = capsule;
options.CustomBar = capsule.bottom + capsule.top - res.statusBarHeight;
} else {
options.CustomBar = res.statusBarHeight + 50;
}
}
})
return options;
}
export default new global(GLOBALOPTIONS);