经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » Vue.js » 查看文章
vue实现手机验证码登录
来源:jb51  时间:2021/11/22 13:41:47  对本文有异议

本文实例为大家分享了vue实现手机验证码登录的具体代码,供大家参考,具体内容如下

验证码

<template>
  <div>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号" size=""
                    maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-row :span="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.code" auto-complete="off" placeholder="请输入验证码" size=""
                        maxlength="4"
                        @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-col>
            <el-col :span="12">
              <div class="login-code">
                <!--验证码组件-->
                <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
                           :disabled="getCodeBtnDisable">{{ codeBtnWord }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!--滑动验证组件-->
        <Verify></Verify>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        </el-form-item>
      </el-form>

    </el-main>
  </div>
</template>

用到的vue验证工具类

export default {
  // 限制只能输入数字(可以输入两位小数点)
  limitInputPointNumber(val) {
    if (val === 0 || val === "0" || val === "" || val === undefined) {
      return "";
    } else {
      let value = null;
      value = val.replace(/[^\d.]/g, ""); // 清除“数字”和“.”以外的字符
      value = value.replace(/\.{2,}/g, "."); // 只保留第一个. 清除多余的
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      return value;
    }
  },

  handleRouteToArray(route) {
    const matchs = route.path.split('/')
    matchs.shift()
    let newMatch = []
    matchs.map((item, i) => {
      if (matchs[i - 1]) {
        item = newMatch[i - 1] + '/' + item
      }
      newMatch.push(item)
    })
    newMatch = newMatch.map(item => {
      return `/${item}`
    })
    return newMatch
  },

  //  密码长度8位以上,须包含大写、小写、数字、特殊符号中的任意3种
  testPassWord: function (str) {
    var rC = {
      lW: '[a-z]',
      uW: '[A-Z]',
      nW: '[0-9]',
      sW: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'
    }
    function Reg (str, rStr) {
      var reg = new RegExp(rStr)
      if (reg.test(str)) return true
      else return false
    }
    if (str.length < 8) {
      return false
    } else {
      var tR = {
        l: Reg(str, rC.lW),
        u: Reg(str, rC.uW),
        n: Reg(str, rC.nW),
        s: Reg(str, rC.sW)
      }
      if ((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s) || (tR.s && tR.u && tR.n) || (tR.s && tR.l && tR.n)) {
        // document.title = "密码符合要求"
        return true
      } else {
        return false
      }
    }
  },

  // 密码验证8-30位任意字符
  pwdReg: /^([0-9a-zA-Z]|(?:&)|(?:~)|(?:!)|(?:@)|(?:#)|(?:\$)|(?:%)|(?:\^)|(?:\*)){8,30}$/,

  // 电话号码验证
  phoneReg: /^1[3|4|5|6|7|8][0-9]{9}$/,

  // 格式化金钱
  formatUSD (val, currency) {
    if (val === '' || val === '--' || val === undefined) {
      return '--'
    }
    // 先判断数据是否有小数点
    let newVal = String(Number(val).toFixed(2))
    // 将科学计数转为正常的字符串显示
    if (newVal.includes('e+')) {
      newVal = Number(newVal).toLocaleString()
      newVal = this.unFormatAmount(newVal)
    }
    let dotIdx = newVal.lastIndexOf('.')
    let dotVal = '.00' // 保留小数点后面的数据
    if (dotIdx >= 0) {
      dotVal = newVal.substr(dotIdx, newVal.length)
      newVal = newVal.slice(0, dotIdx)
    }

    let len = newVal.length
    let arr = []
    let lastIndex = null
    while (len > 0) {
      lastIndex = len
      len -= 3
      arr.unshift(newVal.substring(len, lastIndex))
    }
    val = arr.join(',')

    if (currency) {
      newVal = `${currency} ${val}${dotVal}`
    } else {
      // newVal = `$ ${val}${dotVal}`
      newVal = `¥ ${val}${dotVal}` // 默认人民币
    }
    return newVal
  },

  // 格式化金额数字,不包含小数点,金额符等 输入整数
  formatAmount (val) {
    if (val === '' || val === '--' || val === undefined) {
      return '--'
    }
    if (val === 0 || val === '0') {
      return 0
    }
    // 先判断数据是否有小数点
    let newVal = String(val)
    let dotIdx = newVal.lastIndexOf('.')
    let dotLength = 0
    if (newVal.split('.').length > 1) {
      dotLength = newVal.split('.')[1].length
    }
    let dotVal = '' // 保留小数点后面的数据
    if (dotIdx >= 0) {
      newVal = String(Number(val).toFixed(5))
      dotVal = newVal.substr(dotIdx, dotLength + 1)
      newVal = newVal.slice(0, dotIdx)
    }
    let len = newVal.length
    let arr = []
    let lastIndex = null
    while (len > 0) {
      lastIndex = len
      len -= 3
      arr.unshift(newVal.substring(len, lastIndex))
    }
    val = arr.join(',')
    if (dotVal.length < 2) {
      dotVal = ''
    }
    return val + dotVal
  },

  // 判断数据是否为空
  isEmptyVal (val) {
    if (val === undefined || val === '') {
      return '--'
    } else {
      return val
    }
  },

    // 格式化年月日   type: 中国显示方式(ch)及拼接的方式
  // 注: 只有在接口传参时才需要中国的显示方式,其它为美式
  formatYMD (now, type='ch') {
    if (!now || now === 'null' || now === '--' || now === undefined) {
      return '--'
    }
    if (Number(now)) {
      now = new Date(now)
    }
    // 兼容IE浏览器 , YY-MM-DD 格式
    if (typeof now === 'string' && now.includes('-')) {
      now = this.NewDate(now)
    }
    if (now) {
      let year = ''
      let month = ''
      let date = ''
      // 这里的8位用于返回如 20180423 这样的格式
      if (String(now).length === 8 && String(now).indexOf('-') === -1 && String(now).indexOf('/') === -1) {
        const getNow = String(now)
        return `${getNow.substring(4, 6)}/${getNow.substring(6, 8)}/${getNow.substring(0, 4)}`
      } else {
        now = new Date(now)
        year = now.getFullYear()
        month = now.getMonth() + 1
        date = now.getDate()
      }
      if (month < 10) {
        month = `0${month}`
      }
      if (date < 10) {
        date = `0${date}`
      }
      if (type === 'ch') {
        return `${year}-${month}-${date}`
      } else if (type) {
        return `${year}${type}${month}${type}${date}`
      } else {
        return `${month}/${date}/${year}`
      }
    } else {
      return ''
    }
  },

  // 格式化时间 年,月,日,时,分,秒
  formatDate (now, type) {
    if (!now || now === 'null' || now === '--' || now === undefined) {
      return '--'
    }
    if (now) {
      now = new Date(now)
      let year = now.getFullYear()
      let month = now.getMonth() + 1
      let date = now.getDate()
      let hour = now.getHours()
      let minute = now.getMinutes()
      let second = now.getSeconds()
      if (month < 10) {
        month = `0${month}`
      }
      if (date < 10) {
        date = `0${date}`
      }
      if (hour < 10) {
        hour = `0${hour}`
      }
      if (minute < 10) {
        minute = `0${minute}`
      }
      if (second < 10) {
        second = `0${second}`
      }
      if (type) {
        return `${month}/${date}/${year} ${hour}:${minute}:${second}`
      } else {
        return `${month}-${date}-${year}`
      }
    } else {
      return ''
    }
  },
}

直接放上完整的这样有助于看

<template>
  <div>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="请输入手机号" size=""
                    maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-row :span="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.code" auto-complete="off" placeholder="请输入验证码" size=""
                        maxlength="4"
                        @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-col>
            <el-col :span="12">
              <div class="login-code">
                <!--验证码组件-->
                <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
                           :disabled="getCodeBtnDisable">{{ codeBtnWord }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!--滑动验证组件-->
        <Verify></Verify>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
        </el-form-item>
      </el-form>

    </el-main>
  </div>
</template>

<script>
//导入工具类
import Verify from "@/components/Verify";
import event from "../utils/event"
import common from "@/utils/common";

let params;
export default {
  name: "LoginIphone",
  components: {Verify},
  data() {
    //使用正则表达式验证手机号
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      } else {
        //获取工具类中的手机号正则表达式
        const reg = common.phoneReg
        // console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          //如果验证输入错误就清空
          this.ruleForm.phone = ''
          return callback(new Error('请输入正确的手机号'));
        }
      }
    };

    return {
      ruleForm: {
        phone: '',
        code: '',
      },

      codeBtnWord: '获取验证码', // 获取验证码按钮文字
      // waitTime: 61, // 获取验证码按钮失效时间
      waitTime: 2, // 获取验证码按钮失效时间
      // 校验
      rules: {
        phone: [
          {validator: checkPhone, trigger: 'blur'}
        ],
        code: [
          {required: true, message: '请输入验证密码', trigger: 'blur'}
        ]
      }
    };
  },
  //计算属性computed
  computed: {
    // 控制获取验证码按钮是否可点击
    getCodeBtnDisable: {
      //设置按钮61s
      // get() {
      //   if (this.waitTime === 61) {
      //     if (this.ruleForm.phone) {
      //       return false
      //     }
      //     return true
      //   }
      //   return true
      // }
      get() {
        if (this.waitTime === 2) {
          if (this.ruleForm.phone) {
            return false
          }
          return true
        }
        return true
      },
      // 注意:因为计算属性本身没有set方法,不支持在方法中进行修改,而下面我要进行这个操作,所以需要手动添加
      set() {
      }
    },

  }, methods: {

    getCode() {
      const _this = this
      params = {}
      params.phone = this.ruleForm.phone
      // 调用获取短信验证码接口
      _this.$axios.post('/sendMessage', params).then(res => {
        console.log("--------查看后台响应的值-----", res)
        //把所有的数据存在
        const mydata = res.data.data
        console.log("我在短信接口这利-->", mydata)

        //保存验证码
        params.yz = mydata.vCode

        console.log("我是查看验证码-------" + mydata.vCode)
        console.log("我是查看调用的次数-------" + mydata.count)

        if (res.data.code === 200) {
          this.$message({
            message: '验证码已发送,请稍候...',
            type: 'success',
            center: true
          })
        }
        if (res.data.data.count >= 5) {
          //调用滑块验证的组件
          event.$emit("VERIFY")
        }

      })

      // 因为下面用到了定时器,需要保存this指向
      let that = this
      that.waitTime--
      that.getCodeBtnDisable = true
      this.codeBtnWord = `${this.waitTime}s 后重新获取`
      let timer = setInterval(function () {
        if (that.waitTime > 1) {
          that.waitTime--
          that.codeBtnWord = `${that.waitTime}s 后重新获取`
        } else {
          clearInterval(timer)
          that.codeBtnWord = '获取验证码'
          that.getCodeBtnDisable = false
          // that.waitTime = 61
          that.waitTime = 2
        }
      }, 1000)
    },
    submitForm(formName) {
      const _this = this
      //判断输入的验证码是否为空
      if (this.ruleForm.code != null) {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            _this.$axios.post("/iosLogin", {
              "phone": this.ruleForm.phone,
              "Verification": this.ruleForm.code
            }).then(res => {

              console.log(res.data)
            })


            // console.log("我是提交里面的:", par)
            //
            // const jwt = par.headers['authorization']
            // console.log("我是token->", jwt)
            // const userInfo = par.data.data
            // console.log("查看用户信息=", userInfo)
            //
            // // 把数据共享出去
            // _this.$store.commit("SET_TOKEN", jwt)
            // _this.$store.commit("SET_USERINFO", userInfo)
            //
            // // 获取
            // console.log("我是获取的_this.$store.getters.getUser")
            // console.log(_this.$store.getters.getUser)

            // _this.$router.push("/blogs")

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else {
        this.$message({
          showClose: true,
          message: '请输入错误',
          type: 'error'
        });
      }
    }

  }

}
</script>
<style scoped>
.el-button.disabled-style {
  background-color: #EEEEEE;
  color: #CCCCCC;
}

.demo-ruleForm {
  max-width: 500px;
  margin: 0 auto;
}
</style>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳