SendVerificationCode.vue 2.42 KB
<template>
  <div>
    <div class="sendCodeText" :class="{active:isValue}" @click="sendCode" v-show="show">获取验证码</div>
    <div class="coutdDownText" v-show="!show"><span class="second">{{time}}s</span>后重新获取</div>
  </div>
</template>
<script>
import utils from "@/utils/";
let timer = null;
export default {
  name: 'SendVerificationCode',
  props: {
    coutDownNumber: {
      type: Number,
      default: 60
    },
    phone: {
      type: [Number, String],
    },
    email: {
      type: String
    },
    data: {
      type: Object
    }
  },
  data() {
    return {
      show: true,
      time: 60,
      isValue: false
    }
  },
  watch: {
    // 监控 手机号有值 则获取验证码 增加蓝色
    phone(val) {
      if (val) {
        this.isValue = true
      } else {
        this.isValue = false
      }
    },
    // 监控 邮箱号有值 则获取验证码 增加蓝色
    email(val) {
      if (val) {
        this.isValue = true
      } else {
        this.isValue = false
      }
    },
  },
  methods: {
    sendCode() {
      console.log(this.data.type)
      // 发送手机号验证码
      if (this.data.type == 'phone') {
        // 判断手机号不能为空
        if (!this.phone) {
          Toast('请输入手机号')
          return
        }

        if (!utils.phoneRegCheck(this.phone)) {
          Toast("请输入正确的手机号码!");
          return
        }
      } else {
        // 发送邮件验证码
        if (!this.email) {
          Toast('请输入邮箱')
          return
        }

        if (!utils.emailRegCheck(this.email)) {
          Toast("请输入正确的邮箱格式!");
          return
        }
      }


      this.time = this.coutDownNumber
      this.show = false // 显示倒计时

      if (timer) {
        clearInterval(timer);
      }
      timer = setInterval(() => {
        console.log(this.time)
        if (this.time > 0 && this.time <= this.coutDownNumber) {

          this.time--;
        } else {
          this.show = true
          this.time = this.coutDownNumber
          clearInterval(timer);
          timer = null;
        }
      }, 1000);
    }
  },
  destroyed() {
    clearInterval(timer);
  }
}
</script>
<style lang="less" scoped>
.sendCodeText {
  color: #9c9c9c;
  font-size: 12px;
}
.active {
  color: #106abc;
}
.coutdDownText {
  color: #9c9c9c;
  font-size: 12px;
  .second {
    color: #106abc;
    font-size: 16px;
  }
}
</style>