在应用开发过程中,为了尽量消除冗余代码我们往往会将一些通用的变量或者函数进行抽象以便进行复用,比如baseurl,通用的工具函数等。接下来就总结下uniapp中实现全局变量和全局函数的方法,几乎经常用到的、不经常用到的一些方法都有总结到,包括支付以及其他工具类都有哦

实现

  1. 定义变量和函数
  2. 在main.js中挂载公用属性和公用函数
  3. 页面中使用

优缺点

优点是使用简单,直接将属性或者函数挂载到Vue.prototype,在vue页面中直接通过this.来访问,缺点是只支持vue,不支持nvue

具体演示代码

utils.js

import {
	baseUrl,
	baseUploadPath
} from '@/common/config.js';
/**
 * @description:  验证手机号是否合格
 * @param {*} phoneStr  手机号
 * @return true 合格
 */
export function isPhone(phoneStr) {
	return /^1\d{10}$/.test(phoneStr)
}
/**
 * @description: 验证邮箱
 * @param {*} email 邮箱
 * @return true 合格
 */
export function checkEmail(email) {
	return RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/).test(
		email);
}

/**
 * @description: 验证身份证号是否合格
 * @param {*} idCardStr 生份证号
 * @return true 说明合格
 */
export function isIdCard(idCardStr) {
	let idcardReg =
		/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;
	return idcardReg.test(idCardStr);
}

/**
 * @description:  验证字符串是否为空
 * @param {*} string 
 * @return ture 说明为空 false 说明不为空
 */
export function isEmptyString(string) {
	if (
		string == undefined ||
		typeof string == 'undefined' ||
		!string ||
		string == null ||
		string == '' ||
		/^\s+$/gi.test(string)
	) {
		return true;
	} else {
		return false;
	}
}
/**
 * @description: 
 * @param {any} val - 基本类型数据或者引用类型数据
 * @return {string} - 可能返回的结果有,均为小写字符串 
 * number、boolean、string、null、undefined、array、object、function等
 */
export function getType(val) {
	//判断数据是 null 和 undefined 的情况
	if (val == null) {
		return val + "";
	}
	return typeof(val) === "object" ?
		Object.prototype.toString.call(val).slice(8, -1).toLowerCase() :
		typeof(val);
}

// 验证是否为数字
export function isNumber(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

// 是否为数组
export function isArray(obj) {
	return Object.prototype.toString.call(obj) === '[object Array]';
}

//  是否为空数组
export function isArrayEmpty(val) {
	if (val && val instanceof Array && val.length > 0) {
		return false;
	} else {
		return true;
	}
}
/**
 * @description: 获取url参数字符串没有返回null
 * @param {*} name 路径
 */
export function getQueryString(name) {
	let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	let r = window.location.search.substr(1).match(reg);
	if (r != null) {
		return unescape(r[2]);
	}
	return null;
}

/**
 * @description  函数防抖,用于将多次执行变为最后一次执行
 * @param {function} func - 需要使用函数防抖的被执行的函数。必传
 * @param {Number} wait - 多少毫秒之内触发,只执行第一次,默认1000ms。可以不传
 */
export function debounce(fn, delay) {
	delay = delay || 1000; //默认1s后执行
	let timer = null;
	return function() {
		let context = this;
		let arg = arguments;
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			fn.apply(context, arg);
		}, delay);
	};
}
/**
 * @description  节流函数, 用于将多次执行变为每隔一段时间执行
 * @param fn 事件触发的操作
 * @param delay 间隔多少毫秒需要触发一次事件
 */
export function throttle(fn, delay) {
	let timer = null;
	return () => {
		let context = this;
		let args = arguments;
		if (!timer) {
			timer = setTimeout(() => {
				fn.apply(context, args);
				clearTimeout(timer);
			}, delay);
		}
	};
}

/**
 * @description:  将字符串时间转换为时间戳
 * @param {string} date 时间
 * @return {String} timestamp 时间戳
 */
export function getDateTime(date) {
	let timestamp = '';
	if (date) {
		date = date.substring(0, 19);
		date = date.replace(/-/g, '/'); //必须把日期'-'转为'/'
		timestamp = new Date(date).getTime();
	}
	return timestamp;
}
/**
 * @description uniapp 预览图片
 * @url 图片路径
 * @current 索引
 */
export function previewImage(url, current) {
	var urls = [];
	if (typeof url == 'string') urls.push(url)
	else urls = url
	uni.previewImage({
		urls,
		current: current ? current : 0
	})
}
/**
 * @description  格式化手机号
 **/
export function formatPhone(phone) {
	let tel = phone.slice(0, 3) + '****' + phone.slice(7, 11);
	return tel;
}
/**
 * @description:  uniapp 复制
 * @param {String} info
 */
export function copyText(info) {
	var result;
	// #ifndef H5
	//uni.setClipboardData方法就是讲内容复制到粘贴板
	uni.setClipboardData({
		data: info, //要被复制的内容
		success: () => { //复制成功的回调函数
			uni.showToast({ //提示
				title: '复制成功',
				icon: "none"
			})
		}
	});
	// #endif

	// #ifdef H5 
	let textarea = document.createElement("textarea")
	textarea.value = info
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选中文本内容
	textarea.setSelectionRange(0, info.length)
	uni.showToast({ //提示
		title: '复制成功',
		icon: "none"
	})
	result = document.execCommand("copy")
	textarea.remove()
	// #endif
}

/**
 * @description:  获取当前日期前后多少天的日期,多少天前传正数,多少天后传负数,今天传0
 * @param {*} num 为传入的数字
 * @param {*} time 为传入的指定日期,如果time不传,则默认为当前时间
 */
export function getBeforeDate(num, time) {
	let n = num;
	let d = '';
	if (time) {
		d = new Date(time);
	} else {
		d = new Date();
	}
	let year = d.getFullYear();
	let mon = d.getMonth() + 1;
	let day = d.getDate();
	if (day <= n) {
		if (mon > 1) {
			mon = mon - 1;
		} else {
			year = year - 1;
			mon = 12;
		}
	}
	d.setDate(d.getDate() - n);
	year = d.getFullYear();
	mon = d.getMonth() + 1;
	day = d.getDate();
	let s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
	return s;
}
/**
 * @description:  获取年-月-日
 * @param {String} data  时间戳
 */
export function getDates(data) {
	let timeObj = {};
	data = new Date(data);
	let y = data.getFullYear();
	let m =
		data.getMonth() + 1 < 10 ?
		'0' + (data.getMonth() + 1) :
		data.getMonth() + 1;
	let d = data.getDate() < 10 ? '0' + data.getDate() : data.getDate();
	let w = data.getDay();
	switch (w) {
		case 1:
			w = '星期一';
			break;
		case 2:
			w = '星期二';
			break;
		case 3:
			w = '星期三';
			break;
		case 4:
			w = '星期四';
			break;
		case 5:
			w = '星期五';
			break;
		case 6:
			w = '星期六';
			break;
		case 7:
			w = '星期日';
			break;
	}
	let h = data.getHours() < 10 ? '0' + data.getHours() : data.getHours();
	let mi = data.getMinutes() < 10 ? '0' + data.getMinutes() : data.getMinutes();
	let s = data.getSeconds() < 10 ? '0' + data.getSeconds() : data.getSeconds();
	// 年月日 星期几 时分秒
	timeObj = {
		year: y + '',
		month: m + '',
		day: d + '',
		week: w + '',
		hour: h + '',
		minute: mi + '',
		second: s + ''
	};
	return timeObj;
}

/**
 *  @description 页面跳转
 */
export function urlTo(e) {
	uni.navigateTo({
		url: e
	})
}

/**
 * @description 页面跳转
 */
export function urltabTo(e) {
	uni.switchTab({
		url: e
	})
}

/**
 * @description 页面返回
 */
export function pageBack(e) {
	uni.navigateBack()
}
/**
 * @description: 消息提示框
 * @param {String} msg
 * @param {Boolean} isback 为true时返回上级页面
 */
export function toast(msg = '', isback) {
	uni.showToast({
		title: msg,
		duration: 2000,
		icon: 'none'
	});
	if (isback) {
		setTimeout(function() {
			uni.navigateBack()
		}, 1000)
	}
}

/**
 * @description 弹出提示信息结束后执行方法
 */
export function showMsg(msg, duration = 2000, callback) {
	uni.showToast({
		title: msg,
		icon: 'none',
		duration: duration,
		success: function() {
			setTimeout(callback, duration);
		}
	})
}


/**
 * @description: 微信支付宝拉取支付
 * @param {String} provider 支付方式
 * @param {Object} orderInfo 支付参数
 * @return uni回调
 */
export function uniPay(provider, orderInfo) {
	return new Promise(function(resolve, reject) {
		// #ifdef APP-PLUS
		// APP
		uni.requestPayment({
			provider,
			orderInfo,
			success(res) {
				resolve(res);
			},
			fail(err) {
				reject(err);
			}
		});

		// #endif

		// #ifdef MP-WEIXIN
		// 微信小程序
		uni.requestPayment({
			provider: 'wxpay',
			'timeStamp': orderInfo.timeStamp, // 时间戳从1970年1月1日至今的秒数,即当前的时间。
			'nonceStr': orderInfo.nonceStr, // 随机字符串,长度为32个字符以下
			'package': orderInfo.package, // 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=xx
			'signType': orderInfo.signType, // 签名算法,应与后台下单时的值一致
			'paySign': orderInfo.paySign, // 签名,具体签名方案参见 微信小程序支付文档
			success(res) {
				resolve(res);
			},
			fail(err) {
				reject(err);
			}
		})
		//	#endif

	});
}

/**
 * @description:  h5支付宝支付
 * @param {Object} data 后端返回form表单
 */
export function h5Alipay(data) {
	document.querySelector('body').innerHTML = data;
	document.forms[0].submit();
}

/**
 * @description:   h5 微信内微信支付
 * @param {Object} data  后端返回参数
 */
export function h5Wxpay(data) {
	return new Promise(function(resolve, reject) {
		function onBridgeReady() {
			WeixinJSBridge.invoke(
				'getBrandWCPayRequest', {
					"appId": data.appId,
					"timeStamp": data.timeStamp,
					"nonceStr": data.nonceStr,
					"package": data.packageValue,
					"signType": data.signType,
					"paySign": data.paySign
				},
				function(res) {
					if (res.err_msg == "get_brand_wcpay_request:ok") {
						// 支付成功
						// console.log("utis----h5Wxpay---resolve: ", resolve);
						resolve(res);
					} else {
						// 支付失败
						// console.log("utis----h5Wxpay---resolve: ", resolve);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						})
					}
				});
		}
		if (typeof WeixinJSBridge == "undefined") {
			if (document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			} else if (document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
			}
		} else {
			onBridgeReady();
		}
	});
}
/**
 * @description: 上传图片仅支持一张
 * @param {String} path 上传路径
 */
export function uploadFile(path, filePath) {
	let url = path || baseUploadPath;
	return new Promise((resolve, reject) => {

		uni.uploadFile({
			url: baseUrl + url,
			name: 'file',
			filePath,
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`
			},
			success: (uploadFileRes) => {
				let uploadRes = JSON.parse(uploadFileRes.data);
				resolve(uploadRes);
			},
			fail(err) {
				reject(err)
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}
/**
 * @description: 上传图片仅支持一张
 * @param {String} path 上传路径
 */
export function upload(path) {
	let url = path || baseUploadPath;
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			success: res => {
				uni.showLoading({
					title: '上传中...'
				});
				uni.uploadFile({
					url: baseUrl + url,
					name: 'file',
					filePath: res.tempFilePaths[0],
					header: {
						'Authorization': `Bearer ${uni.getStorageSync('token')}`
					},
					success: (uploadFileRes) => {
						let uploadRes = JSON.parse(uploadFileRes.data);
						resolve(uploadRes);
					},
					fail(err) {
						reject(err)
					},
					complete() {
						uni.hideLoading();
					}
				});
			}
		})
	});
}

/**
 * @description: 保存图片
 * @param {String} filePath 图片路径
 */
export function saveImg(filePath) {
	// #ifdef APP-PLUS
	uni.saveImageToPhotosAlbum({
		filePath,
		success() {
			toast('保存成功')
		}
	});
	// #endif
	// #ifdef H5 || MP-WEIXIN
	const aEle = document.createElement('a');
	aEle.download = '图片'; // 设置下载的文件名
	aEle.href = this.filePath;
	document.body.appendChild(aEle);
	aEle.click();
	aEle.remove(); // 下载之后把创建的元素删除
	// #endif
}


/**
 * @description: 数字转单位
 * @param {Number} value
 */
export function bigNumberTransform(value = 0) {
	let param = '';
	let k = 10000,
		sizes = ['', '万', '亿', '万亿'],
		i;
	if (value < k) {
		param = value
	} else {
		i = Math.floor(Math.log(value) / Math.log(k));
		param = ((value / Math.pow(k, i))).toFixed(2) + sizes[i];
	}
	return param;
}

/**
 * @description:  搜索高亮关键字
 * @param {Array} keywords 返回的数组
 * @param {String} keyword 搜索的keyword
 */
export function drawCorrelativeKeyword(keywords, keyword) {
	var len = keywords.length,
		keywordArr = [];
	for (var i = 0; i < len; i++) {
		var row = keywords[i];
		var html = row[0].replace(keyword, "<span style='color: #EB645E;'>" + keyword + "</span>");
		html = '<div>' + html + '</div>';
		var tmpObj = {
			keyword: row[0],
			htmlStr: html
		};
		keywordArr.push(tmpObj)
	}
	return keywordArr;
}

/**
 * @description: app 打开app
 * @param {String} path
 */
export function openPlatform(path) {
	plus.runtime.openURL(path, err => {
		if (err) console.log(err);
	});
}

/**
 * @description: 获取应用缓存
 * @return
 */
export function formatSize() {
	plus.cache.calculate((size) => {
		let sizeCache = parseInt(size);
		if (sizeCache == 0) {
			this.fileSizeString = "0B";
		} else if (sizeCache < 1024) {
			this.fileSizeString = sizeCache + "B";
		} else if (sizeCache < 1048576) {
			this.fileSizeString = (sizeCache / 1024).toFixed(2) + "KB";
		} else if (sizeCache < 1073741824) {
			this.fileSizeString = (sizeCache / 1048576).toFixed(2) + "MB";
		} else {
			this.fileSizeString = (sizeCache / 1073741824).toFixed(2) + "GB";
		}
	});
}

/**
 * @description: 清理缓存
 * @return
 */
export function clearCache() {
	let os = plus.os.name;
	if (os == 'Android') {
		let main = plus.android.runtimeMainActivity();
		let sdRoot = main.getCacheDir();
		let files = plus.android.invoke(sdRoot, "listFiles");
		let len = files.length;
		for (let i = 0; i < len; i++) {
			let filePath = '' + files[i];
			plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
				if (entry.isDirectory) {
					entry.removeRecursively((entry) => {
						uni.showToast({
							title: '缓存清理完成',
							duration: 2000
						});
						formatSize();
					}, (e) => {
						console.log(e.message)
					});
				} else {
					entry.remove();
				}
			}, (e) => {
				console.log('文件路径读取失败')
			});
		}
	} else { // ios  
		plus.cache.clear(() => {
			uni.showToast({
				title: '缓存清理完成',
				duration: 2000
			});
			this.formatSize();
		});
	}
};

/**
 * @description: 对比版本号 支持比对	("3.0.0.0.0.1.0.1", "3.0.0.0.0.1")	("3.0.0.1", "3.0")	("3.1.1", "3.1.1.1") 
 * @param {String} v1
 * @param {String} v2
 * @return 
 * v1 > v2 return 1
 * v1 < v2 return -1
 * v1 == v2 return 0
 */
export function compareVersion(v1 = '0', v2 = '0') {
	v1 = String(v1).split('.')
	v2 = String(v2).split('.')
	const minVersionLens = Math.min(v1.length, v2.length);

	let result = 0;
	for (let i = 0; i < minVersionLens; i++) {
		const curV1 = Number(v1[i])
		const curV2 = Number(v2[i])

		if (curV1 > curV2) {
			result = 1
			break;
		} else if (curV1 < curV2) {
			result = -1
			break;
		}
	}

	if (result === 0 && (v1.length !== v2.length)) {
		const v1BiggerThenv2 = v1.length > v2.length;
		const maxLensVersion = v1BiggerThenv2 ? v1 : v2;
		for (let i = minVersionLens; i < maxLensVersion.length; i++) {
			const curVersion = Number(maxLensVersion[i])
			if (curVersion > 0) {
				v1BiggerThenv2 ? result = 1 : result = -1
				break;
			}
		}
	}

	return result;
};


/**
 * @description: 校验对象的值是否为空
 * @param {Object} obj
 * @return {String || Boolean} true 校验通过 String 返回为空的key
 */
export function validateObject(obj) {
	for (var key in obj) {
		if (obj[key] === null || obj[key] == '' || obj[key] == 0 || obj[key].length == 0) {
			return key;
		}
	}
	return true;
}

main.js

import * as Utils from '@/common/utils.js';

Vue.prototype.utils = Utils;

页面使用

this.utils.upload();
this.utils.toast('提示一下');

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐