自制一个发送验证码的10秒倒计时js效果

<template>
    <div class="conten1">
        <input class="code" type="text" v-model="code">
        <button @click="sendCode()">{{codeBtnText}}</button>
    </div>
</template>
<script>
export default {
    name: "",
    data(){
      return{
        code:'',
        codeBtnText:'获取验证码',
      }
    },
    created:function(){},
    methods:{
      //发送验证码事件
        sendCode(){
             if(this.codeBtnText!='获取验证码') return            //倒计时中点击按钮不可再次发送
            let token = sessionStorage.getItem('token')
            let data = {
                token:token,
                username:this.way.trim(),
                methodPost:true,
            }
            //可先做非空判断
             this.axios(config.API + '/api/user/verification_code/xxx',data,{}).then((res)=>{
                   console.log(res)
                   this.countDown()
              })
        },
        // 验证码倒计时
        countDown(){
            let count = 10
            let timer = setInterval(()=>{                                   
                count--
                console.log(count)
                this.codeBtnText = count+'秒后再次获取'                 //注意this指向,使用箭头函数或let that = this
                if(count==0){
                    this.codeBtnText = '获取验证码'
                    clearInterval(timer)
                }
            },1000)
        },
    },
    mounted:function(){} 
}
</script>
<style scoped>

</style>

猜你喜欢

转载自www.cnblogs.com/wd163/p/13169932.html