//文件:utils/util.js
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
function checkMobile (mobile){
return RegExp(/^1[3456789]d{9}$/).test(mobile); //验证手机号
}
function passWord(pws){
// return RegExp(/^[A-Za-z0-9]{6}$/).test(pws); //验证密码
return RegExp(/^(?![0-9]+$)(?![a-zA-Z]+$)[A-Za-z0-9]{6,22}$/).test(pws); //验证密码
}
/**
* 获得状态栏高度
*/
var getStatusBarHeight= ()=> {
var immersed = 0;
var ms=(/Html5Plus/.+s(.*(Immersed/(d+.?d*).*))/gi).exec(navigator.userAgent);
if(ms&&ms.length>=3){ // 当前环境为沉浸式状态栏模式
immersed=parseFloat(ms[2]);// 获取状态栏的高度
}
return immersed;
}
/* 验证码倒计时
that this
time 倒计时时间
disable 是否禁止点击
*/
var codeDown=(that,time,disable)=>{
if(that[time]<=1){
that[time]=60;
that[disable]=false;
return false;
}
that[disable]=true
that[time]=that[time]-1
setTimeout(()=>{codeDown(that,time,disable)},1000)
}
// 各种校验
let verify={
// 手机号验证
mobile(mobile){
let myreg=/^[1][3,4,5,6,7,8][0-9]{9}$/;
return (mobile==""?'手机号不能为空':'')||(!myreg.test(mobile)?'手机号输入有误,请重新输入':'')||true
},
// 验证码验证
code(code){
return code==""?'验证码不能为空':true
},
pass:"",
// 密码验证
password(pass){
let myreg=/^[a-zA-Z0-9_-]{6,22}$/;
verify.pass=pass
return (pass==""?'密码不能为空':'')||(!myreg.test(pass)?'密码输入有误,请重新输入':'')||true
},
// 再次输入密码
password2(pass2){
return (pass2==""?'请再次输入密码':'')||(pass2!=verify.pass?'两次密码输入不一致,请重新输入':'')||true
}
}
// html装换
let escape2Html=(str)=>{
var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; }).replace(/<img/gi, '<img style="max-100%;height:auto;" ');
}
export default {
formatTime: formatTime,
checkMobile,
passWord,
verify,
codeDown,
escape2Html,
getStatusBarHeight,
}
//main.js
import util from './utils/util'
Vue.prototype.$util = util;//挂载vue的实例上
//需要引入的页面
<template>
<p class="code" @click="handleCode">{{!disable?'获取验证码':codeTime+'s'}}</p>
</template>
<script>
export default {
data() {
return {
codeTime: 60,
disable: false
};
},
methods: {
//获取验证码
handleCode() {
if (!this.disable) {
this.$util.codeDown(this, "codeTime", "disable");
}
},
},
}
</script>
//封装成公共文件util.js,在vue的main.js中引入,挂载在vue实例上 => Vue.prototype.$util = util;
/* 验证码倒计时
that this
time 倒计时时间
disable 是否禁止点击
*/
var codeDown=(that,time,disable)=>{
if(that[time]<=1){
that[time]=60;
that[disable]=false;
return false;
}
that[disable]=true
that[time]=that[time]-1
setTimeout(()=>{codeDown(that,time,disable)},1000)
}
export default {
codeDown,
}