vue获取验证码以及倒计时60秒方法

完整的获取验证码方法,上干货。

<template>
    <div class="login-content">
      <van-cell-group>
        <van-field label="手机号" type="tel" v-model="phone" :error="phoneError && !phone" maxlength="11" placeholder="请输入手机号" />
        <van-field
          v-model="verifycode"
          center
          clearable
          label="验证码"
          placeholder="请输入验证码">
          <van-button slot="button" size="small" type="primary" @click="sendVerifycode()" :disabled="!disabledCodeBtn">{{codeText}}</van-button>
        </van-field>
      </van-cell-group>
      <div class="btn padding">
        <van-button type="primary" size="large" @click="login()">验证身份</van-button>
      </div>
    </div>
</template>

// 以上是 vant-ui
<script>
  import {Field, CellGroup, Button, Toast} from 'vant'
  import api from 'api/api_lib'  // api换成自己的

  export default {
    name: 'login',
    data () {
      return {
        phone: '',
        verifycode: '',
        codeText:'获取',
        disabledCodeBtn: true
      }
    },
    components: {
      [Field.name]: Field,
      [CellGroup.name]: CellGroup,
      [Button.name]: Button,
      [Toast.name]: Toast
    },
    methods: {
    // 向后台要验证码方法
      async sendVerifycode(){
        if(this.verifyPhone()){
          Toast(this.verifyPhone())
        } else {
          let res = await api.pp.sms.getVerifyCode(this.phone)
          //  用手机号向后台换取验证码,发送成功则开始调用倒计时分方法
          if(res){
            this.countDown(60)
          }
        }
      },
      // 表单校验方法
      verifyPhone(){
        if(!this.phone){
          return '请输入手机号'
        } else if(this.phone.length !== 11){
          return '请输入11位手机号'
        } else {
          return false
        }
      },
  	// 倒计时方法
      countDown (time) {
        if (time === 0) {
          this.disabledCodeBtn = true
          this.codeText = "获取"
          return
        } else {
          this.disabledCodeBtn = false;
          this.codeText = '重新发送(' + time + ')'
          time--
        }
        setTimeout(()=> {
          this.countDown(time)
        }, 1000)
      },
      // 登录
      login(){
        if(this.verifyPhone()){
          Toast(this.verifyPhone())
        } else {
          let params = {
            phone: this.phone,
            code: this.verifycode
          }
          // 这里写登录的接口
        }
      }
    },
  }
</script>

<style scoped>
.login-content{
  padding-top: 35%;
}
  .padding{
    padding: 40px 15px;
  }
</style>

猜你喜欢

转载自blog.csdn.net/BoReFrontEnd/article/details/89711433