vue实现验证码登录demo

不废话直接上demo

html

 <el-form
   :model="ruleForm"
   :rules="rules"
   ref="ruleForm"
 >
   <el-form-item  prop="mobile">
     <el-input v-model="ruleForm.mobile" placeholder="请输入手机号"></el-input>
   </el-form-item>
   <el-form-item  prop="code">
     <el-input @keyup.enter.native="submitForm('ruleForm')" v-model="ruleForm.code" placeholder="请输入验证码">
       <el-button v-if="sending" slot="append" @click="getCode">获取验证码</el-button>
       <el-button v-else slot="append" :disabled="disabled">{{second}}秒后获取</el-button>
     </el-input>
   </el-form-item>
   <el-form-item>
     <el-button style="width:100%" type="danger" @click="submitForm('ruleForm')">登录</el-button>
   </el-form-item>
 </el-form>
  

data

  data() {
    const validate_mobile = (rule, value, callback) => {
        let reg = /^[1]([3-9])[0-9]{9}$/;
        if (!value) {
          callback("请输入手机号");
        } else if (!reg.test(value)) {
          callback("请输入正确的手机号");
        } else {
          callback();
        }
      };
    return {
      rules: {
        mobile: [{ required: true, validator: validate_mobile, trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
      },
      ruleForm:{
        mobile:'',
        code:''
      },
      sending: true,    //是否发送验证码
      disabled: false,  //是否禁发验证码
      second:59,        //倒计时间
    };
  },

methods

  //methods

  //倒计时
   timeDown() {
      let result = setInterval(()=>{
      --this.second;
      if(this.second < 0) {
        clearInterval(result);
        this.sending  = true;
        this.disabled = false;
        this.second = 59;
        }   
      }, 1000);
    },
    
    //获取验证码
    getCode(){
      if(!this.sending){
        return;
      }
      if(this.ruleForm.mobile == ''){
        this.$message.error('请输入手机号')
      }else{
      //api接口封装请求
        this.$http.user.getCode({
          mobile:this.ruleForm.mobile
        }).then(res=>{
          this.sending  = false;
          this.disabled = true;
          this.timeDown();
        })
      }
    },
  //提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log('提交')
        }
      });
    },

效果

在这里插入图片描述
点击获取,按钮禁用并开始倒计时
在这里插入图片描述
笔记:
api 封装后面会分享,目前是想到哪就写哪
后续还会分享微信钉钉字节小程序,uniapp, react, 常用操作,和踩过的坑

Logo

前往低代码交流专区

更多推荐