wo-user-part-uniapp/index.js

161 lines
5.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

module.exports = {
clog(...message){
console.log('【【【【【【【【【【',
getCurrentPages().length>0 ? getCurrentPages().pop().route : 'pages/Welcome', // 在首页时getApp() 或 getCurrentPages() 有可能获取不到。
...message,
'】】】】】】】】】】】')
},
sleep: (ms)=>new Promise((resolve, reject)=>setTimeout(resolve, ms)),
async request(obj){
obj.method = 'POST'
obj.url = this.makeUrl(obj.url)
if (uni.getStorageSync('_passtoken')) {
obj.header = obj.header || {}
obj.header._passtoken = uni.getStorageSync('_passtoken')
}
if (obj.data && (typeof(obj.method) === 'undefined' || obj.method==='GET')) { // 如果不是 POST 方法,要额外把参数JSON化
for (let key in obj.data) {
obj.data[key] = JSON.stringify(obj.data[key])
}
}
console.log('👇 👇 👇 👇 < Request > 👇 👇 👇 👇 ', obj, '👆 👆 👆 👆 < /Request > 👆 👆 👆 👆')
let [error, response] = await uni.request(obj)
console.log('⬇️ ⬇️ ⬇️ ⬇️ < Response > ⬇️ ⬇️ ⬇️ ⬇️ ', response, '⬆️ ⬆️ ⬆️ ⬆️ < /Response > ⬆️ ⬆️ ⬆️ ⬆️')
return [error, response]
},
async uploadFile(obj){
obj.url = this.makeUrl(obj.url)
if (uni.getStorageSync('_passtoken')) {
obj.header = obj.header || {}
obj.header._passtoken = uni.getStorageSync('_passtoken')
}else{
return [{ errMsg:'offline user cannot upload files' }, null]
}
if (obj.formData) { // multer 不会自动处理 JSON 数据,必须前后端配合处理
for (let key in obj.formData) {
obj.formData[key] = JSON.stringify(obj.formData[key])
}
}
if (!obj.name) obj.name = 'file'
let [error, response] = await uni.uploadFile(obj)
if (response && response.data) {
try {
response.data = JSON.parse(response.data)
}catch (exception) {}
}
return [error, response]
},
openUrl(url){
// #ifdef APP-PLUS
plus.runtime.openURL(url)
// #endif
// #ifdef H5
window.open(url, "_blank")
// #endif
},
getPlatform(){
if (window && window.navigator) {
var agent = navigator.userAgent.toLowerCase()
if (agent.match(/MicroMessenger/i) == "micromessenger") {
return 'H5.wechat';
} else {
return 'H5'
}
}
switch(uni.getSystemInfoSync().platform){
case 'android': return 'app.android'
case 'ios': return 'app.ios'
case 'devtools': return 'devtools'
default: return 'unknown'
}
},
showToast({type, icon, image, title, duration}){
let pageNow = getCurrentPages().pop()
if (pageNow.$refs && pageNow.$refs.toast) {
pageNow.$refs.toast.open({type, content:title, duration})
}else {
// #ifndef APP-PLUS
if (!image){
image = `../static/Common.${type?type:'info'}.png`
}
uni.showToast({icon, image, title, duration})
// #endif
// #ifdef APP-PLUS
if (uni.getSystemInfoSync().platform==='android') {
uni.showToast({icon:'none', title, duration})
}
// #endif
}
},
setBarTitles({windowTitle, pageTitle}={}){
let page = this.$store ? this : getCurrentPages().pop()
uni.setNavigationBarTitle({ title: pageTitle || page.i18nText[page.$store.state.i18n.activeLang].tPageTitle })
// #ifdef H5
document.title = windowTitle || page.$store.getters['i18n/getAppName'] || page.appName // 必须放在 setNavigationBarTitle 之后,否则会被其覆盖掉。
// #endif
page.$store.commit('i18n/setTabbar') // 必须要在有 tab 的页面里重置才有效果
},
localeText(){
let page = this.$store ? this : getCurrentPages().pop()
return page.i18nText[page.$store.state.i18n.activeLang]
},
formatMoney(value, decimal){
return Number(value).toFixed(decimal||2)
},
formatPercent(value, decimal){
return `${Number(value*100).toFixed(decimal||2)}%`
},
formatDate(date, format){
if (!(date instanceof Date)){
date = new Date(date)
}
if (!date.toJSON()) {
date = new Date()
}
format = (format && typeof format==='string')
? format
: 'yyyy-mm-dd HH:MM:SS'
let o = {
'm+': date.getMonth() + 1, //月份
'q+': Math.floor((date.getMonth() + 3) / 3), //季度
'd+': date.getDate(), //日
'H+': date.getHours(), //小时
'M+': date.getMinutes(), //分
'S+': date.getSeconds(), //秒
's': date.getMilliseconds() //毫秒
}
if (/(y+)/.test(format))
format = format.replace(RegExp.$1, (`${date.getFullYear()}`).substr(4 - RegExp.$1.length))
for (var k in o){
if (new RegExp(`(${k})`).test(format))
format = format.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : ((`00${o[k]}`).substr((`${o[k]}`).length)))
}
return format
},
hash(data, {hasher='sha256', salt, input='utf8', output='hex'}={}){
if (typeof(data)!=='string' && !(data instanceof Buffer) && !(data instanceof DataView))
data=JSON.stringify(data)
if (salt && typeof(salt)==='string')
data=data+salt
let inputEncoding=input // my.INPUT_LIST.indexOf(option.input)>=0?option.input:my.INPUT // 'utf8', 'ascii' or 'latin1' for string data, default to utf8 if not specified; ignored for Buffer, TypedArray, or DataView.
let outputEncoding=(output==='buf')?undefined:output // (my.OUTPUT_LIST.indexOf(output)>=0?output:my.OUTPUT) // option.output: 留空=》默认输出hex格式或者手动指定 'buf', hex', 'latin1' or 'base64'
return require('crypto').createHash(hasher).update(data, inputEncoding).digest(outputEncoding)
},
}