摘要:在 电商系统 的前端开发过程中,会遇到多个页面用到同一种方法的使用,比如时间戳转换指定格式,对一个对象进行深拷贝,正则验证等,我们可以把这些方法进行封装,以便于项目使用与后期维护
一、 创建
首先在ui-utils目录下创建三个js文件:
Foundation.js 放一些常用的基础方法
RegExp.js 放正则验证
index.js 导入导出文件
二、 Foundation.js 封装代码
/**
* 将unix时间戳转换为指定格式
* @param unix 时间戳【秒】
* @param format 转换格式
* @returns {*|string}
*/export function unixToDate(unix, format) {
if (!unix) return unix
let _format = format || 'yyyy-MM-dd hh:mm:ss'
const d = new Date(unix * 1000)
const o = {
'M+': d.getMonth() + 1,
'd+': d.getDate(),
'h+': d.getHours(),
'm+': d.getMinutes(),
's+': d.getSeconds(),
'q+': Math.floor((d.getMonth() + 3) / 3),
S: d.getMilliseconds()
}
if (/(y+)/.test(_format)) _format = _format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length))
for (const 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
}
/**
* 将时间转unix时间戳
* @param date
* @returns {number} 【秒】
*/export function dateToUnix(date) {
let newStr = date.replace(/:/g, '-')
newStr = newStr.replace(/ /g, '-')
const arr = newStr.split('-')
const datum = new Date(Date.UTC(
arr[0],
arr[1] - 1,
arr[2],
arr[3] - 8 || -8,
arr[4] || 0,
arr[5] || 0
))
return parseInt(datum.getTime() / 1000)
}
/**
* 对一个对象进行深拷贝
* @param object
* @returns {*}
*/export function deepClone(object) {
let str
let newobj = object.constructor === Array ? [] : {}
if (typeof object !== 'object') {
return object
} else if (window.JSON) {
str = JSON.stringify(object)
newobj = JSON.parse(str)
} else {
for (const i in object) {
if (object.hasOwnProperty(i)) {
newobj[i] = typeof object[i] === 'object' ? deepClone(object[i]) : object[i]
}
}
}
return newobj
}
/**
* 货币格式化
* @param price
* @returns {string}
*/export function formatPrice(price) {
if (typeof price !== 'number') return price
return String(Number(price).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
/**
* 手机号隐私保护
* 隐藏中间四位数字
* @param mobile
* @returns {*}
*/export function secrecyMobile(mobile) {
mobile = String(mobile)
if (!/\d{11}/.test(mobile)) {
return mobile
}
return mobile.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$3')
}
/**
* 随机生成指定长度的字符串
* @param length
* @returns {string}
*/export function randomString(length = 32) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
const maxPos = chars.length
let _string = ''
for (let i = 0; i < length; i++) {
_string += chars.charAt(Math.floor(Math.random() * maxPos))
}
return _string
}
/**
* 计算当前时间到第二天0点的倒计时[秒]
* @returns {number}
*/export function theNextDayTime() {
const nowDate = new Date()
const time = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 1, 0, 0, 0).getTime() - nowDate.getTime()
return parseInt(time / 1000)
}
/**
* 计算传秒数的倒计时【天、时、分、秒】
* @param seconds
* @returns {{day : *, hours : *, minutes : *, seconds : *}}
*/export function countTimeDown(seconds) {
const leftTime = (time) => {
if (time < 10) time = '0' + time
return time + ''
}
return {
day: leftTime(parseInt(seconds / 60 / 60 / 24, 10)),
hours: leftTime(parseInt(seconds / 60 / 60 % 24, 10)),
minutes: leftTime(parseInt(seconds / 60 % 60, 10)),
seconds: leftTime(parseInt(seconds % 60, 10))
}
}
三、 RegExp.js 正则验证封装代码
// 手机号
export const mobile = /^0?(13[0-9]|14[0-9]|15[0-9]|16[0-9]|17[0-9]|18[0-9]|19[0-9])[0-9]{8}$/
// 电子邮箱
export const email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
// 密码【6-20位 包括特殊字符】
export const password = /^[A-Za-z0-9!#$%^&*.~,]{6,20}$/
// 正整数【不包含0】
export const integer = /^[1-9]\d*$/
// 正整数【包含0】
export const positiveInteger = /^[0-9]\d*$/
// 金钱
export const money = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
// 纳税识别号
export const TINumber = /(^[a-zA-Z0-9]{15}$)|(^[a-zA-Z0-9]{18}$)|(^[a-zA-Z0-9]{20}$)/
// 身份证
export const IDCard = /^[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)$/
// 账户名称【汉字、字母、数字、“-”、“_”的组合】以其开头并且匹配一个或任意多个
export const userName = /^[A-Za-z0-9_\-\u4e00-\u9fa5]+$/
// URL
export const URL = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
// 固话
export const TEL = /0\d{2,3}-\d{7,8}/
四、 index.js 导入导出文件
导入Foundation与RegExp封装方法
import * as Foundation from './Foundation'
import * as RegExp from './RegExp'
导出
export {
Foundation,
RegExp
}
五、 项目中的使用
引入
import { Foundation } from '@/ui-utils'
在项目中使用 Foundation
/** 开始倒计时 */ startCountDown() {
this.interval = setInterval(() => {
let { time } = this;
if (time <= 0) {
clearInterval(this.interval);
this.$alert(this.onlyOne ? '本轮限时抢购已结束!' : '下一轮限时抢购已经开始啦!请确认查看', function () {
location.reload()
});
return false
}
time -= 1;
const timeText = Foundation.countTimeDown(time);
this.$set(this, 'times', Foundation.countTimeDown(time));
this.$set(this, 'time', time)
}, 1000)
},
引入
import { RegExp } from '@/ui-utils'
在项目中使用RegExp
if (!RegExp.integer.test(_value)) {
this.$message.error('您的输入不合法!');
return
}
if (!RegExp.mobile.test(value)) {
callback(new Error('请输入正确的手机号!'))
} else {
callback()
}