常用的功能函数
(1): 功能函数
1: 回到顶部
Vue.prototype.$scrollTo = (x = 0, y = 0, type = 'smooth') => {
window.scrollTo({
top: x,
left: y,
behavior: type // 滚动行为:smooth平滑滚动,instant瞬间滚动,默认值auto,等同于instant
})
}
2: 判断传递过来的值是否为空
//判断传过来的值是否为空
export function isNull(data) {
if(data == '' || data == null || data == undefined ){
return true
}
return false
}
// 或者使用includes
export function isNull(data) {
let arr = [undefined,"",false,null]
return arr.includes(data)
}
// 或者使用空值合并(注意空值合并只会检验null和undefined,不推荐)
// !!(data?? "") 这样写的也有个弊端就是对于 输入框中 输入的 0 NaN 和 false都是返回为false
export function isNull(data) {
let flag = !!(data?? "")
return flag
}
3: 函数防抖
export function debounce(fn,delay=500) {
let timer = null;
return function() {
if(timer) clearTimeout(timer)
timer = setTimeout(()=>{
fn.apply(this,arguments)
},delay)
}
}
4: 函数节流
export function throttle(fn,wait=500) {
let previous = 0;
return function() {
let now = Date.now();
if(now - previous > wait) {
fn.apply(this,arguments)
}
}
}
5: 验证手机号
export function validatePhone(phone) {
let pattern = /^1[3,4,5,7,8,9]\d{9}$/;
if (pattern.test(phone)) {
return true;
} else {
return false;
}
}
6: 验证邮箱
export function validateEmail(email) {
let pattern = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
if (pattern.test(email)) {
return true;
} else {
return false;
}
}
7: 验证密码
export function isPassword(pwd) {
let pattern = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/;
return pattern.test(pwd);
}
8: 证件照
/**
*
* @param {string} number - 证件号码
* @param {number | string} type = 1 - 证件类型 1:身份证 2:护照
*/
export function isIDNo(number, type = 1) {
let pattern;
const _type = +type;
switch (_type) {
case 1:
pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
break;
case 2:
pattern = /^[a-zA-Z0-9]{5,17}$/;
break;
default:
return true;
}
return pattern.test(number);
}
9: 验证对象是否为空
/**
* 判断是否为空对象
* @param {Object} obj
* @returns {boolean}
*/
第一种写法:
export function isEmptyObj(obj) {
let isEmpty = true;
for (let key in obj) {
if (key) {
isEmpty = false;
break;
}
}
return isEmpty;
}
第二种写法:
export function isEmptyObj1(obj) {
let obj1 = JSON.stringify(obj)
if(obj1 === "{}"){
return true
}
return false
}
10: 日期格式转换
// 第一种写法
function dateTimeFiter(num) {
// 时间戳数据处理
let date = new Date(num);
// 时间戳为10位需*1000,时间戳为13位的话不需乘1000
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? "0" + MM : MM; // 月补0
let d = date.getDate();
d = d < 10 ? "0" + d : d; // 天补0
let h = date.getHours();
h = h < 10 ? "0" + h : h; // 小时补0
let m = date.getMinutes();
m = m < 10 ? "0" + m : m; // 分钟补0
let s = date.getSeconds();
s = s < 10 ? "0" + s : s; // 秒补0
return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
}
// 第二种写法
function dateTimeFiter(num) {
// 时间戳数据处理
let date = new Date(num);
// 时间戳为10位需*1000,时间戳为13位的话不需乘1000
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM.toString().padStart(2,"0")
let d = date.getDate();
d = d.toString().padStart(2,"0")
let h = date.getHours();
h = h.toString().padStart(2,"0")
let m = date.getMinutes();
m = m.toString().padStart(2,"0")
let s = date.getSeconds();
s = s.toString().padStart(2,"0")
return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
}
// 第三种写法
function dateTimeFiter(num) {
// 时间戳数据处理
let date = new Date(num);
// 时间戳为10位需*1000,时间戳为13位的话不需乘1000
let y = date.getFullYear();
let MM = date.getMonth() + 1;
MM = MM < 10 ? "0" + MM : MM; // 月补0
let d = date.getDate();
d = padNum(d)
let h = date.getHours();
h = padNum(h)
let m = date.getMinutes();
m = padNum(m)
let s = date.getSeconds();
s = padNum(h)
return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
}
function padNum(num) {
return num < 10 ? "0" + num : num
}
export default dateTimeFiter
如果日期复杂可以使用 day.js 或者 moment.js
11: 获取文件的大小
bytesToSize(bytes) {
if (bytes === 0) return '0 KB';
var k = 1000, // or 1024
sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
},
使用
import tool from '@/common/tool.js';
filters: {
formatCurrentSize(value) {
return tool.bytesToSize(value);
}
},
<text slot="footer">{{ currentSize | formatCurrentSize }}</text>
12: 生成随机字符串
const random = function(min, max) { // 生成随机数范围
if (arguments.length === 2) {
return Math.floor(min + Math.random() * ((max + 1) - min))
}
else {
return null
}
}
export default random
13: 获取search参数并且组成一个对象
var paramsString = "https://blog.csdn.net/lxs19930928?spm=1010.2135.3001.5421&name=张三"
function getSearchParams(url) {
var arr = url.split("?")
var searchParams = new URLSearchParams(arr[1]);
var obj = {}
for (let [key,val] of searchParams) {
obj[key]=val
}
return obj
}
getSearchParams(paramsString) // {spm: '1010.2135.3001.5421', name: '张三'}
// 或者使用qs转换
import qs from 'qs'
function getSearchParams(url) {
let index = url.lastIndexOf("?")+1
var params = url.slice(index)
let parseObj = qs.parse(params)
console.log("parseObj",parseObj) // {spm: '1010.2135.3001.5421', name: '张三'}
return parseObj
}
export default getSearchParams
14: 千分位分隔符
var num=12345678.32423432;
function (num) {
return num.toString().replace(/\d+/, (p) => {
return p.replace(/\d(?=(\d{3})+$)+/g, (p1, p2) => {
return p1 + ','
})
})
}
console.log(regForm(num));//12,345,678.32423432
export default regForm
(2):支付宝小程序常用的功能函数
/*
各种环境check方法:
1.支付宝浏览器 checkAlipay
2.支付宝小程序 checkAlipayApp
3.平台app checkApp
4.ios浏览器 checkIos
5.安卓浏览器 checkAndroid
6.微信浏览器 checkWeixin
7.微信小程序 checkWeixinApp
8.获取APP版本号 getAppVersion
9.获取APP ticket getAppTicket
*/
// 支付宝浏览器
const checkAlipay = function () {
if (navigator.userAgent.toLowerCase().indexOf('alipayclient') > -1) {
return true
} else {
return false
}
}
// 支付宝小程序
const checkAlipayApp = function () {
if (navigator.userAgent.toLowerCase().indexOf('alipayclient') > -1 && (navigator.userAgent.toLowerCase().indexOf('miniprogram') > -1 ||
navigator.userAgent.toLowerCase().indexOf('alipayide/webview') > -1)) {
return true
} else {
return false
}
}
// 平台app
const checkApp = function () {
if (/(pigcmso2oreallifeapp)/.test(navigator.userAgent.toLowerCase())) {
return true
} else {
return false
}
}
// ios浏览器
const checkIos = function () {
if (/(iphone|ipad|ipod)/.test(navigator.userAgent.toLowerCase())) {
return true
} else {
return false
}
}
// 安卓浏览器
const checkAndroid = function () {
if (/(android)/.test(navigator.userAgent.toLowerCase())) {
return true
} else {
return false
}
}
// 微信浏览器
const checkWeixin = function () {
if (/(micromessenger)/.test(navigator.userAgent.toLowerCase())) {
return true
} else {
return false
}
}
// 微信小程序
const checkWeixinApp = function () {
if (window.__wxjs_environment === 'miniprogram' || (checkWeixin() && /(miniprogram)/.test(navigator.userAgent.toLowerCase()))) {
return true
} else {
return false
}
}
// 获取APP版本号
const getAppVersion = function () {
var reg = /versioncode=(.*?),/;
var arr = reg.exec(navigator.userAgent.toLowerCase());
if (arr == null) {
return '85'
} else {
return arr[1]
}
}
const getAppTicket = function () {
var reg = /ticket=(.*?),/
var arr = reg.exec(navigator.userAgent)
if (arr == null) {
return ''
} else {
return arr[1]
}
}
export default {
checkAlipay,
checkAlipayApp,
checkApp,
checkIos,
checkAndroid,
checkWeixin,
checkWeixinApp,
getAppVersion,
getAppTicket
}
(3):moment.js
下载moment.js
yarn add -D moment
moment(new Date()).format('YYYY-MM-DD HH:mm:ss'); // 2022-01-01 16:37:44
moment("2021-10-23").format('YYYY-MM-DD HH:mm:ss'); // 2021-10-23 00:00:00
moment("2021-10-23").format('YYYY-MM-DD HH:mm:ss'); // 2021-10-20 00:00:00
import moment from "moment";
/**
* 格式化时间
* @param {*} dataStr
* @param {*} pattern
*/
const formatDateTime = function(dataStr, pattern = "YYYY-MM-DD HH:mm:ss") {
return dataStr ? moment(dataStr).format(pattern) : "";
};
/**
* 时间格式化
* @param {*} dataStr
* @param {*} pattern
*/
const formatTime = function(dataStr) {
return formatDateTime(dataStr, "HH:mm:ss");
};
/**
* 日期格式化
* @param {*} dataStr
* @param {*} pattern
*/
const formatDate = function(dataStr) {
return formatDateTime(dataStr, "YYYY-MM-DD");
};
export default {
formatDateTime,
formatTime,
formatDate,
};