You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

324 lines
7.7 KiB
JavaScript

import { isGetLocation } from "./location.js";
const tabBarList = [
"/pages/index/index",
"/pages/cat/cat",
"/pages/shoppingCart/index",
"/pages/my/my",
];
export default {
// 跳转页面
toUrl(url, type) {
console.log(url);
if (
tabBarList.some((item) => url.indexOf(item) !== -1) &&
type != "reLaunch"
) {
uni.switchTab({
url: url,
});
return;
}
if (type == "redirectTo") {
uni.redirectTo({
url,
});
} else if (type == "reLaunch") {
uni.reLaunch({
url,
});
} else {
uni.navigateTo({
url,
});
}
},
// 后退页面
backTo(num = 1) {
const current = getCurrentPages();
if (current.length <= 1) {
this.toUrl("/pages/home/home");
} else {
uni.navigateBack({
delta: num,
});
}
},
/**
* @des 复制
*/
copy(data, toast = "内容已复制") {
uni.setClipboardData({
data,
success: () => {
uni.showToast({
title: toast,
icon: 'none'
})
},
});
},
/**
* @des 将 Date 转化为指定格式的String
* @des 月(m)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
* @des 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
* @des 例子: DateFormat("yyyy-MM-dd hh:mm:ss.s","2006-07-02") ==> 2006-07-02 08:09:04.423
* @param fmt
* @param date
* @returns {String}
*/
DateFormat(fmt, date) {
const newDate = date || new Date();
const o = {
"M+": newDate.getMonth() + 1, // 月份
"d+": newDate.getDate(), // 日
"h+": newDate.getHours(), // 小时
"m+": newDate.getMinutes(), // 分
"s+": newDate.getSeconds(), // 秒
"q+": Math.floor((newDate.getMonth() + 3) / 3), // 季度
S: newDate.getMilliseconds(), // 毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(newDate.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1 ?
o[k] :
("00" + o[k]).substr(("" + o[k]).length)
);
}
}
return fmt;
},
getRouterInfo() {
let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
let curRoute = routes[routes.length - 1].route // 获取当前页面路由,也就是最后一个打开的页面路由
let curParam = routes[routes.length - 1].options || []; //获取路由参数
const params = Object.entries(curParam).reduce((param, [key, val], index) => {
if (index === 0) {
return param + key + '=' + val
}
return param += '&' + key + '=' + val
}, "?")
return [curRoute, params]
},
loginOut() {
const [curRoute, curRouteParam] = this.getRouterInfo()
uni.setStorageSync("backPage", "/" + curRoute + curRouteParam)
uni.clearStorage();
this.toUrl("/pages/login/index", "redirectTo");
},
kmUnit(m) {
var v;
if (typeof m === 'number' && !isNaN(m)) {
if (m >= 1000) {
v = (m / 1000).toFixed(2) + ' km'
} else {
v = m.toFixed(2) + ' m'
}
} else {
v = '0 m'
}
return v;
},
objectToQueryString(obj) {
var params = '';
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (params !== '') {
params += '&';
}
params += encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]);
}
}
return '?' + params;
},
oneValues(url) {
var name, value;
var str = url; //取得整个地址栏
var num = str.indexOf("?");
str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ]
let obj = {};
var arr = str.split("&"); //各个参数放到数组里
for (var i = 0; i < arr.length; i++) {
num = arr[i].indexOf("=");
if (num > 0) {
name = arr[i].substring(0, num);
value = arr[i].substr(num + 1);
obj[name] = value;
}
}
return obj;
},
// 下载图片
downloadImage(imageUrl) {
return new Promise((resolve, reject) => {
function downloadFile() {
uni.downloadFile({
url: imageUrl,
success: function (res) {
// 检查下载是否成功
if (res.statusCode === 200) {
console.log('图片下载成功:', res.tempFilePath);
// 将图片保存到相册
uni.saveImageToPhotosAlbum({
filePath: res.tempFilePath,
success: function () {
console.log('图片保存成功');
resolve(res.tempFilePath); // 返回下载的图片路径
},
fail: function (saveErr) {
console.error('图片保存失败:', saveErr);
reject(new Error('图片保存失败'));
}
});
} else {
// 下载失败,拒绝 Promise
uni.showToast({
title: "保存失败,请检查是否开启权限 (2)",
icon: "none",
});
console.error('图片下载失败:', res);
reject(new Error('图片下载失败'));
}
},
fail: function (err) {
uni.showToast({
title: "保存失败,请检查是否开启权限 (1)",
icon: "none",
});
// 下载失败,拒绝 Promise
console.error('图片下载失败:', err);
reject(err);
}
});
}
// #ifdef MP-WEIXIN
//获取相册授权
uni.getSetting({
success(res) {
if (!res.authSetting["scope.writePhotosAlbum"]) {
uni.authorize({
scope: "scope.writePhotosAlbum",
success(e) {
//这里是用户同意授权后的回调
downloadFile();
},
fail(fail) {
uni.showModal({
title: "提示",
content: "需要获取您的相册保存权限,请到小程序的设置中打开授权",
success(res) {
if (res.confirm) {
wx.openSetting()
}
}
})
},
});
} else {
//用户已经授权过了
downloadFile();
}
},
});
// #endif
// #ifdef MP-ALIPAY
downloadFile();
// #endif
});
},
// 判断参数中是否存在 distributor_id 属性,并将其存储到本地
// 将传入的 url 参数解析为对象,并保存到本地
saveDistributorIdToLocal(params, url) {
try {
if (url) {
return this.saveDistributorIdToLocal(this.oneValues(url))
}
if (params && typeof params === 'object' && 'distributor_id' in params) {
// 如果 params 是一个对象,并且包含 distributor_id 属性,将其存储到本地
const distributorId = params.distributor_id;
uni.setStorageSync('distributor_id', distributorId);
return distributorId
} else {
// 如果 params 不符合条件,则将 distributor_id 设置为 0
uni.setStorageSync('distributor_id', 0);
}
} catch (error) {
console.log(error);
}
},
// 小程序跳转
navigateToMiniProgramWithParams(appId, path, params) {
uni.navigateToMiniProgram({
appId: appId,
path: path,
extraData: params,
success: function (res) {
console.log('跳转成功', res);
},
fail: function () {
uni.$u.toast("跳转失败:" + JSON.stringify({ appId, path, params }))
}
});
},
dateFormat(date, fmt = 'yyyy-MM-dd hh:mm:ss') {
date = new Date(date)
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
},
// 判断位置权限
isGetLocation: isGetLocation,
};