uniapp vue超全公用函数 工具库

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

实现

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

优缺点

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

目录结构

具体演示代码

utils.js

import {
	baseUrl
} from '@/request/url.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: 消息提示框
 * @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 upload(path) {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			success: function(res) {
				uni.showLoading({
					title: '上传中...'
				});
				uni.uploadFile({
					url: baseUrl + path,
					name: 'file',
					filePath: res.tempFilePaths[0],
					header: {
						'Authorization': `${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 {String} htmlStr 富文本字符串
 * @returns 文字 图片路径
 */
export function plainTextContent(htmlStr) {
	const htmlTagsRegex = /<[^>]+>/g; // 匹配html标签的正则表达式
	const text = htmlStr.replace(htmlTagsRegex, ''); // 提取纯文本
	const urls = htmlStr.match(/(?<=src=")(.+?)(?=")/g);
	let url = null;
	urls && urls.length ? url = urls[0] : null
	return {
		text,
		url
	};
}

/**
 * @description: 数字转单位
 * @param {Number} value
 */
export function bigNumberTransform(value) {
	let param = '';
	let k = 10000,
		sizes = ['', 'W', '亿', '万亿'],
		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 {String} str 带标签的字符串
 * @return {Number} 字符串长度
 */
export function strLength(str) {
	return str.replace(/<\/?[^>]*>/g, '').length
}
/**
 * @description: 提取富文本中文字和图片
 * @param {String} htmlStr 富文本字符串
 * @returns 文字 图片路径
 */
export function plainTextContent(htmlStr) {
	const htmlTagsRegex = /<[^>]+>/g; // 匹配html标签的正则表达式
	const text = htmlStr.replace(htmlTagsRegex, ''); // 提取纯文本
	const urls = htmlStr.match(/(?<=src=")(.+?)(?=")/g);
	let url = null;
	urls && urls.length ? url = urls[0] : null
	return {
		text,
		url
	};
}
/**
 * @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打开微信小程序
 * @param {Object} data
 */
export function openWeAppInfo(data) {
	let {
		path,
		weUserName
	} = data;
	plus.share.getServices(
		res => {
			let sweixin = null;
			for (let i in res) {
				if (res[i].id == 'weixin') {
					sweixin = res[i];
				}
			}
			//唤醒微信小程序
			if (sweixin) {
				sweixin.launchMiniProgram({
					id: weUserName, //微信开放平台 --- 绑定的微信小程序的 --- 原始id
					type: 0, //小程序版本  0-正式版; 1-测试版; 2-体验版。
					path: path //小程序的页面,用传的参数在小程序接值判断跳转指定页面
				});
			} else {
				console.log("未安装微信逻辑")
			}
		}
	);
}
/**
 * @description: app 打开app
 * @param {String} path
 */
export function openPlatform(path) {
	plus.runtime.openURL(path, err => {
		if (err) console.log(err);
	});
}

main.js

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

Vue.prototype.utils = Utils;

页面使用

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

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值