VUE中获取短信验证码,倒计时

890 阅读1分钟
<template>
    <label for="">手机验证码</label>
    <input type="text" placeholder="请输入短信验证码" v-model="phone">
    <button v-show="show"  class="btn1" @click="getCode">获取短信验证码</button>
    <button v-show="!show" class="btn2" disabled="disabled">{{auth_time}} 秒后重新发送</button>
</template>


<script>
export default {
    data(){
        return{
            phone:'',//手机号
            auth_time: 60,//倒计时默认60s
            show:true,//默认显示获取验证码按钮
        }
    },
    methods:{
        getCode () {
            this.$http.post('api/takeout/index.php?w=login&t=send_code', {
                phone:this.phone,
            }).then((res) => {
                let data = res.data;
                if( data.status == 0 ){
                    this.$toast(data.msg);
                }
                else if( data.status == 1 ){
                    this.$toast(data.msg);//获取成功
                    this.show = false;//显示倒计时按钮
                    
                    //每隔一秒执行一次auth_time--,当auth_time的值<=0,显示获取验证码按钮,清除定时器,auth_time重新赋值为60s
                    var auth_timetimer =  setInterval(()=>{
                        this.auth_time--;
                        if(this.auth_time<=0){
                            this.show = true;
                            clearInterval(auth_timetimer);
                            this.auth_time = 60;
                        }
                    }, 1000);
                }
            });
        },
    },
</script>