获取验证码,60s后重新获取验证码按钮处理

简单写一下html部分 

  <el-form
    ref="registform"
    :model="registerForm"
    :rules="registerRules"
     >
    <el-form-item prop="phone">
      <el-input
        ref="phone"
        v-model="registerForm.phone"
        placeholder="请输入手机号"
        name="phone"
        type="text"
      />
    </el-form-item>
    <el-button
      native-type="button"
      @click="handleGetCode"
      :disabled="!canGetCode"
    >{{ getCodeBtn.btnText }}
    </el-button>
  </el-form>

js部分

<script>
import { sendcode } from "@/api/register" // 引入获取验证码的api
import { validatePhone ,validateCode } from "@/utils/validate" //验证规则
export default {
  name: 'Register',
  data() {
    return {
      getCodeBtn: {
        timer: null,
        seconds: 60,
        btnText: '获取验证码',
      },
      registerForm:{
        phone:"",
        code:""
      },
      registerRules:{
        phone:[
          {
            validator: validatePhone,
            message: "", //验证错误时的提示文字
            trigger: "blur",
          },
        ],
        code:[
          {
            validator: validateCode,
            message: "",
            trigger: "blur",
          },
        ]
      }
    };
  },
  computed: {
    canGetCode() {
      return this.getCodeBtn.btnText === '获取验证码';
    },
  },
  methods: {
   async handleGetCode() {
      if (!this.registerForm.phone) {
        this.$message({
          message: '手机号不能为空',
          type: "warning",
        });
        return false;
      }
      try{
        const data = { phone:this.registerForm.phone }
        const {code} = await sendcode(data)
        if (code === 200) {
          this.$message({
            message: "验证码发送成功!",
            type: "success",
          });
          // 请求成功后 改变按钮文字
          this.initgetCodeTimer();
        }
      }catch(err){
        window.console.error(err);
      }
    },
    initgetCodeTimer() {
      if (this.getCodeBtn.timer) {
        window.clearInterval(this.getCodeBtn.timer);
        this.getCodeBtn.timer = null;
      }
      let count = this.getCodeBtn.seconds;
      this.getCodeBtn.btnText = `重新获取(${count})`;
      this.getCodeBtn.timer = window.setInterval(() => {
        count--;
        if (count === 0) {
          if (this.getCodeBtn.timer) {
            window.clearInterval(this.getCodeBtn.timer);
            this.getCodeBtn.timer = null;
            this.getCodeBtn.btnText = '获取验证码';
          }
          return;
        }
        this.getCodeBtn.btnText = `重新获取(${count})`;
      }, 1000);
    },
  },
};
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值