vue獲取(短信or郵箱)驗證碼組件

<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

https://github.com/woshiitdaniu/vue-getcode-components

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章