開箱即用的vue獲取驗證碼元件
<template> <button :style="config.cssSet?config.cssSet:''" class="common-getCodeBtn" @click="togetCode" :disabled="isGetting" >{{ message?message:config.initText }}</button> </template>
<script> import { toSendShortCode,toSendEmailCode,toCheckPhoneNum,toCheckEmailNum } from '../../utils/api' export default { name:'getCode', props:{ config:{//樣式配置 type: Object }, inputVal:{//引數值 type:String }, types:{//1代表電話號碼 2代表郵箱 type:Number } }, data() { return { message:'', isGetting:false//防止重複點選 } }, methods:{ togetCode() { let inputVal = this.inputVal; console.log("傳進來的引數:"+inputVal) //檢驗傳入的引數格式是否正確 let checkResult = this.types ===1 ? toCheckPhoneNum(inputVal) : toCheckEmailNum(inputVal) if( !checkResult ){ this.$emit('resultFun',1) return; } this.isGetting = true; let t = 120; let _this = this; for( let i = 1; i <= t; i++ ) { window.setTimeout(()=>{ _this.update_a(i,t) }, i * 1000); } this.toSendShortCodes(inputVal) }, update_a( num, t ) { //倒數 if( num == t ) { this.message = this.$t("components_getCode.sendAgain"); this.isGetting = false; } else { var printnr = t - num; this.message = printnr + this.$t("components_getCode.timeToSend"); } }, toSendShortCodes(p) { //呼叫傳送api let result = this.types ===1 ? toSendShortCode({ "phoneCode": 86, 'phone': p, 'type': 7, }) : toSendEmailCode({ 'email': p }) this.$emit('resultFun',result) } } } </script>
<style> </style>
該元件兼顧了簡訊和郵箱驗證碼的傳送,以及vue國際化開發,詳細的封裝過程請移步本人github