vue實現手機驗證碼登錄
更新時間:2021年11月22日 12:35:20 作者:qq_25995697
這篇文章主要為大家詳細介紹了vue實現手機驗證碼登錄,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了vue實現手機驗證碼登錄的具體代碼,供大家參考,具體內容如下
驗證碼
<template>
<div>
<el-main>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="手機號" prop="phone">
<el-input v-model="ruleForm.phone" placeholder="請輸入手機號" size=""
maxlength="11"></el-input>
</el-form-item>
<el-form-item label="驗證碼" prop="code">
<el-row :span="24">
<el-col :span="12">
<el-input v-model="ruleForm.code" auto-complete="off" placeholder="請輸入驗證碼" size=""
maxlength="4"
@keyup.enter.native="submitForm('ruleForm')"></el-input>
</el-col>
<el-col :span="12">
<div class="login-code">
<!--驗證碼組件-->
<el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
:disabled="getCodeBtnDisable">{{ codeBtnWord }}
</el-button>
</div>
</el-col>
</el-row>
</el-form-item>
<!--滑動驗證組件-->
<Verify></Verify>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">登錄</el-button>
</el-form-item>
</el-form>
</el-main>
</div>
</template>
用到的vue驗證工具類
export default {
// 限制只能輸入數字(可以輸入兩位小數點)
limitInputPointNumber(val) {
if (val === 0 || val === "0" || val === "" || val === undefined) {
return "";
} else {
let value = null;
value = val.replace(/[^\d.]/g, ""); // 清除“數字”和“.”以外的字符
value = value.replace(/\.{2,}/g, "."); // 只保留第一個. 清除多余的
value = value
.replace(".", "$#$")
.replace(/\./g, "")
.replace("$#$", ".");
value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能輸入兩個小數
return value;
}
},
handleRouteToArray(route) {
const matchs = route.path.split('/')
matchs.shift()
let newMatch = []
matchs.map((item, i) => {
if (matchs[i - 1]) {
item = newMatch[i - 1] + '/' + item
}
newMatch.push(item)
})
newMatch = newMatch.map(item => {
return `/${item}`
})
return newMatch
},
// 密碼長度8位以上,須包含大寫、小寫、數字、特殊符號中的任意3種
testPassWord: function (str) {
var rC = {
lW: '[a-z]',
uW: '[A-Z]',
nW: '[0-9]',
sW: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'
}
function Reg (str, rStr) {
var reg = new RegExp(rStr)
if (reg.test(str)) return true
else return false
}
if (str.length < 8) {
return false
} else {
var tR = {
l: Reg(str, rC.lW),
u: Reg(str, rC.uW),
n: Reg(str, rC.nW),
s: Reg(str, rC.sW)
}
if ((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s) || (tR.s && tR.u && tR.n) || (tR.s && tR.l && tR.n)) {
// document.title = "密碼符合要求"
return true
} else {
return false
}
}
},
// 密碼驗證8-30位任意字符
pwdReg: /^([0-9a-zA-Z]|(?:&)|(?:~)|(?:!)|(?:@)|(?:#)|(?:\$)|(?:%)|(?:\^)|(?:\*)){8,30}$/,
// 電話號碼驗證
phoneReg: /^1[3|4|5|6|7|8][0-9]{9}$/,
// 格式化金錢
formatUSD (val, currency) {
if (val === '' || val === '--' || val === undefined) {
return '--'
}
// 先判斷數據是否有小數點
let newVal = String(Number(val).toFixed(2))
// 將科學計數轉為正常的字符串顯示
if (newVal.includes('e+')) {
newVal = Number(newVal).toLocaleString()
newVal = this.unFormatAmount(newVal)
}
let dotIdx = newVal.lastIndexOf('.')
let dotVal = '.00' // 保留小數點后面的數據
if (dotIdx >= 0) {
dotVal = newVal.substr(dotIdx, newVal.length)
newVal = newVal.slice(0, dotIdx)
}
let len = newVal.length
let arr = []
let lastIndex = null
while (len > 0) {
lastIndex = len
len -= 3
arr.unshift(newVal.substring(len, lastIndex))
}
val = arr.join(',')
if (currency) {
newVal = `${currency} ${val}${dotVal}`
} else {
// newVal = `$ ${val}${dotVal}`
newVal = `¥ ${val}${dotVal}` // 默認人民幣
}
return newVal
},
// 格式化金額數字,不包含小數點,金額符等 輸入整數
formatAmount (val) {
if (val === '' || val === '--' || val === undefined) {
return '--'
}
if (val === 0 || val === '0') {
return 0
}
// 先判斷數據是否有小數點
let newVal = String(val)
let dotIdx = newVal.lastIndexOf('.')
let dotLength = 0
if (newVal.split('.').length > 1) {
dotLength = newVal.split('.')[1].length
}
let dotVal = '' // 保留小數點后面的數據
if (dotIdx >= 0) {
newVal = String(Number(val).toFixed(5))
dotVal = newVal.substr(dotIdx, dotLength + 1)
newVal = newVal.slice(0, dotIdx)
}
let len = newVal.length
let arr = []
let lastIndex = null
while (len > 0) {
lastIndex = len
len -= 3
arr.unshift(newVal.substring(len, lastIndex))
}
val = arr.join(',')
if (dotVal.length < 2) {
dotVal = ''
}
return val + dotVal
},
// 判斷數據是否為空
isEmptyVal (val) {
if (val === undefined || val === '') {
return '--'
} else {
return val
}
},
// 格式化年月日 type: 中國顯示方式(ch)及拼接的方式
// 注: 只有在接口傳參時才需要中國的顯示方式,其它為美式
formatYMD (now, type='ch') {
if (!now || now === 'null' || now === '--' || now === undefined) {
return '--'
}
if (Number(now)) {
now = new Date(now)
}
// 兼容IE瀏覽器 , YY-MM-DD 格式
if (typeof now === 'string' && now.includes('-')) {
now = this.NewDate(now)
}
if (now) {
let year = ''
let month = ''
let date = ''
// 這里的8位用于返回如 20180423 這樣的格式
if (String(now).length === 8 && String(now).indexOf('-') === -1 && String(now).indexOf('/') === -1) {
const getNow = String(now)
return `${getNow.substring(4, 6)}/${getNow.substring(6, 8)}/${getNow.substring(0, 4)}`
} else {
now = new Date(now)
year = now.getFullYear()
month = now.getMonth() + 1
date = now.getDate()
}
if (month < 10) {
month = `0${month}`
}
if (date < 10) {
date = `0${date}`
}
if (type === 'ch') {
return `${year}-${month}-${date}`
} else if (type) {
return `${year}${type}${month}${type}${date}`
} else {
return `${month}/${date}/${year}`
}
} else {
return ''
}
},
// 格式化時間 年,月,日,時,分,秒
formatDate (now, type) {
if (!now || now === 'null' || now === '--' || now === undefined) {
return '--'
}
if (now) {
now = new Date(now)
let year = now.getFullYear()
let month = now.getMonth() + 1
let date = now.getDate()
let hour = now.getHours()
let minute = now.getMinutes()
let second = now.getSeconds()
if (month < 10) {
month = `0${month}`
}
if (date < 10) {
date = `0${date}`
}
if (hour < 10) {
hour = `0${hour}`
}
if (minute < 10) {
minute = `0${minute}`
}
if (second < 10) {
second = `0${second}`
}
if (type) {
return `${month}/${date}/${year} ${hour}:${minute}:${second}`
} else {
return `${month}-${date}-${year}`
}
} else {
return ''
}
},
}
直接放上完整的這樣有助于看
<template>
<div>
<el-main>
<el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="手機號" prop="phone">
<el-input v-model="ruleForm.phone" placeholder="請輸入手機號" size=""
maxlength="11"></el-input>
</el-form-item>
<el-form-item label="驗證碼" prop="code">
<el-row :span="24">
<el-col :span="12">
<el-input v-model="ruleForm.code" auto-complete="off" placeholder="請輸入驗證碼" size=""
maxlength="4"
@keyup.enter.native="submitForm('ruleForm')"></el-input>
</el-col>
<el-col :span="12">
<div class="login-code">
<!--驗證碼組件-->
<el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
:disabled="getCodeBtnDisable">{{ codeBtnWord }}
</el-button>
</div>
</el-col>
</el-row>
</el-form-item>
<!--滑動驗證組件-->
<Verify></Verify>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">登錄</el-button>
</el-form-item>
</el-form>
</el-main>
</div>
</template>
<script>
//導入工具類
import Verify from "@/components/Verify";
import event from "../utils/event"
import common from "@/utils/common";
let params;
export default {
name: "LoginIphone",
components: {Verify},
data() {
//使用正則表達式驗證手機號
const checkPhone = (rule, value, callback) => {
if (!value) {
return callback(new Error('手機號不能為空'));
} else {
//獲取工具類中的手機號正則表達式
const reg = common.phoneReg
// console.log(reg.test(value));
if (reg.test(value)) {
callback();
} else {
//如果驗證輸入錯誤就清空
this.ruleForm.phone = ''
return callback(new Error('請輸入正確的手機號'));
}
}
};
return {
ruleForm: {
phone: '',
code: '',
},
codeBtnWord: '獲取驗證碼', // 獲取驗證碼按鈕文字
// waitTime: 61, // 獲取驗證碼按鈕失效時間
waitTime: 2, // 獲取驗證碼按鈕失效時間
// 校驗
rules: {
phone: [
{validator: checkPhone, trigger: 'blur'}
],
code: [
{required: true, message: '請輸入驗證密碼', trigger: 'blur'}
]
}
};
},
//計算屬性computed
computed: {
// 控制獲取驗證碼按鈕是否可點擊
getCodeBtnDisable: {
//設置按鈕61s
// get() {
// if (this.waitTime === 61) {
// if (this.ruleForm.phone) {
// return false
// }
// return true
// }
// return true
// }
get() {
if (this.waitTime === 2) {
if (this.ruleForm.phone) {
return false
}
return true
}
return true
},
// 注意:因為計算屬性本身沒有set方法,不支持在方法中進行修改,而下面我要進行這個操作,所以需要手動添加
set() {
}
},
}, methods: {
getCode() {
const _this = this
params = {}
params.phone = this.ruleForm.phone
// 調用獲取短信驗證碼接口
_this.$axios.post('/sendMessage', params).then(res => {
console.log("--------查看后臺響應的值-----", res)
//把所有的數據存在
const mydata = res.data.data
console.log("我在短信接口這利-->", mydata)
//保存驗證碼
params.yz = mydata.vCode
console.log("我是查看驗證碼-------" + mydata.vCode)
console.log("我是查看調用的次數-------" + mydata.count)
if (res.data.code === 200) {
this.$message({
message: '驗證碼已發(fā)送,請稍候...',
type: 'success',
center: true
})
}
if (res.data.data.count >= 5) {
//調用滑塊驗證的組件
event.$emit("VERIFY")
}
})
// 因為下面用到了定時器,需要保存this指向
let that = this
that.waitTime--
that.getCodeBtnDisable = true
this.codeBtnWord = `${this.waitTime}s 后重新獲取`
let timer = setInterval(function () {
if (that.waitTime > 1) {
that.waitTime--
that.codeBtnWord = `${that.waitTime}s 后重新獲取`
} else {
clearInterval(timer)
that.codeBtnWord = '獲取驗證碼'
that.getCodeBtnDisable = false
// that.waitTime = 61
that.waitTime = 2
}
}, 1000)
},
submitForm(formName) {
const _this = this
//判斷輸入的驗證碼是否為空
if (this.ruleForm.code != null) {
this.$refs[formName].validate((valid) => {
if (valid) {
_this.$axios.post("/iosLogin", {
"phone": this.ruleForm.phone,
"Verification": this.ruleForm.code
}).then(res => {
console.log(res.data)
})
// console.log("我是提交里面的:", par)
//
// const jwt = par.headers['authorization']
// console.log("我是token->", jwt)
// const userInfo = par.data.data
// console.log("查看用戶信息=", userInfo)
//
// // 把數據共享出去
// _this.$store.commit("SET_TOKEN", jwt)
// _this.$store.commit("SET_USERINFO", userInfo)
//
// // 獲取
// console.log("我是獲取的_this.$store.getters.getUser")
// console.log(_this.$store.getters.getUser)
// _this.$router.push("/blogs")
} else {
console.log('error submit!!');
return false;
}
});
} else {
this.$message({
showClose: true,
message: '請輸入錯誤',
type: 'error'
});
}
}
}
}
</script>
<style scoped>
.el-button.disabled-style {
background-color: #EEEEEE;
color: #CCCCCC;
}
.demo-ruleForm {
max-width: 500px;
margin: 0 auto;
}
</style>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
全局安裝 Vue cli3 和 繼續(xù)使用 Vue-cli2.x操作
這篇文章主要介紹了全局安裝 Vue cli3 和 繼續(xù)使用 Vue-cli2.x操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09

