vue realizes mobile phone verification code login


In this paper, we share the specific code of vue to realize mobile phone verification code login for your reference. The specific contents are as follows

Verification code

<template>
  <div>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label=" Mobile phone number " prop="phone">
          <el-input v-model="ruleForm.phone" placeholder=" Please enter your mobile phone number " size=""
                    maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label=" Verification code " prop="code">
          <el-row :span="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.code" auto-complete="off" placeholder=" Please enter the verification code " size=""
                        maxlength="4"
                        @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-col>
            <el-col :span="12">
              <div class="login-code">
                <!-- Verification code component -->
                <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
                           :disabled="getCodeBtnDisable">{{ codeBtnWord }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- Sliding verification component -->
        <Verify></Verify>

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

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

vue validation tool classes used

export default {
  //  Limit number entry ( You can enter two decimal places )
  limitInputPointNumber(val) {
    if (val === 0 || val === "0" || val === "" || val === undefined) {
      return "";
    } else {
      let value = null;
      value = val.replace(/[^\d.]/g, ""); //  Clear "number" and " . Characters other than "
      value = value.replace(/\.{2,}/g, "."); //  Keep only the 1 A .  Clear the redundant
      value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //  You can only enter two decimals
      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
  },

  //   Password length 8 Bits above, must contain any of uppercase, lowercase, numbers and special symbols 3 Species
  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 = " Password meets the requirements "
        return true
      } else {
        return false
      }
    }
  },

  //  Password authentication 8-30 Bit arbitrary character
  pwdReg: /^([0-9a-zA-Z]|(?:&)|(?:~)|(?:!)|(?:@)|(?:#)|(?:\$)|(?:%)|(?:\^)|(?:\*)){8,30}$/,

  //  Telephone number verification
  phoneReg: /^1[3|4|5|6|7|8][0-9]{9}$/,

  //  Format money
  formatUSD (val, currency) {
    if (val === '' || val === '--' || val === undefined) {
      return '--'
    }
    //  First judge whether the data has a decimal point
    let newVal = String(Number(val).toFixed(2))
    //  Convert scientific count to normal string display
    if (newVal.includes('e+')) {
      newVal = Number(newVal).toLocaleString()
      newVal = this.unFormatAmount(newVal)
    }
    let dotIdx = newVal.lastIndexOf('.')
    let dotVal = '.00' //  Keep the data after the decimal point
    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}` //  Default RMB
    }
    return newVal
  },

  //  Formatted amount figures, excluding decimal points, amount marks, and so on   Enter an integer
  formatAmount (val) {
    if (val === '' || val === '--' || val === undefined) {
      return '--'
    }
    if (val === 0 || val === '0') {
      return 0
    }
    //  First judge whether the data has a decimal point
    let newVal = String(val)
    let dotIdx = newVal.lastIndexOf('.')
    let dotLength = 0
    if (newVal.split('.').length > 1) {
      dotLength = newVal.split('.')[1].length
    }
    let dotVal = '' //  Keep the data after the decimal point
    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
  },

  //  Judge whether the data is empty or not
  isEmptyVal (val) {
    if (val === undefined || val === '') {
      return '--'
    } else {
      return val
    }
  },

    //  Formatting Year, Month and Day    type:  Chinese display mode (ch) And the way of splicing
  //  Note :  Chinese display mode is only needed when interface parameters are transmitted , Others are American
  formatYMD (now, type='ch') {
    if (!now || now === 'null' || now === '--' || now === undefined) {
      return '--'
    }
    if (Number(now)) {
      now = new Date(now)
    }
    //  Compatible IE Browser   ,  YY-MM-DD  Format
    if (typeof now === 'string' && now.includes('-')) {
      now = this.NewDate(now)
    }
    if (now) {
      let year = ''
      let month = ''
      let date = ''
      //  Here's 8 Bit is used to return the  20180423  Such a format
      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 ''
    }
  },

  //  Formatting time   Year, month, day, hour, minute, second
  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 ''
    }
  },
}

Put the whole one directly, which helps to see

<template>
  <div>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label=" Mobile phone number " prop="phone">
          <el-input v-model="ruleForm.phone" placeholder=" Please enter your mobile phone number " size=""
                    maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label=" Verification code " prop="code">
          <el-row :span="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.code" auto-complete="off" placeholder=" Please enter the verification code " size=""
                        maxlength="4"
                        @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-col>
            <el-col :span="12">
              <div class="login-code">
                <!-- Verification code component -->
                <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
                           :disabled="getCodeBtnDisable">{{ codeBtnWord }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- Sliding verification component -->
        <Verify></Verify>

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

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

<script>
// Import tool class
import Verify from "@/components/Verify";
import event from "../utils/event"
import common from "@/utils/common";

let params;
export default {
  name: "LoginIphone",
  components: {Verify},
  data() {
    // Validating Mobile Phone Numbers Using Regular Expressions
    const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error(' Mobile phone number cannot be empty '));
      } else {
        // Gets the mobile phone number regular expression in the tool class
        const reg = common.phoneReg
        // console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          // Empty if validation input is incorrect
          this.ruleForm.phone = ''
          return callback(new Error(' Please enter the correct mobile phone number '));
        }
      }
    };

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

      codeBtnWord: ' Get verification code ', //  Get Verification Code Button Text
      // waitTime: 61, //  Get the expiration time of the verification code button
      waitTime: 2, //  Get the expiration time of the verification code button
      //  Calibration
      rules: {
        phone: [
          {validator: checkPhone, trigger: 'blur'}
        ],
        code: [
          {required: true, message: ' Please enter the authentication password ', trigger: 'blur'}
        ]
      }
    };
  },
  // Calculate attributes computed
  computed: {
    //  Controls whether the Get Verification Code button is clickable
    getCodeBtnDisable: {
      // Set button 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
      },
      //  Note: Because the calculated property itself does not set Method, it is not supported to modify in the method, but I will do this next, so I need to add it manually
      set() {
      }
    },

  }, methods: {

    getCode() {
      const _this = this
      params = {}
      params.phone = this.ruleForm.phone
      //  Call the interface for obtaining SMS verification code
      _this.$axios.post('/sendMessage', params).then(res => {
        console.log("-------- View the value of the background response -----", res)
        // Save all the data
        const mydata = res.data.data
        console.log(" I'm on the SMS interface -->", mydata)

        // Save verification code
        params.yz = mydata.vCode

        console.log(" I'm checking the verification code -------" + mydata.vCode)
        console.log(" I'm checking the number of calls -------" + mydata.count)

        if (res.data.code === 200) {
          this.$message({
            message: ' Please wait while the verification code has been sent ...',
            type: 'success',
            center: true
          })
        }
        if (res.data.data.count >= 5) {
          // Components that invoke slider validation
          event.$emit("VERIFY")
        }

      })

      //  Because the timer is used below, it needs to be saved this Point
      let that = this
      that.waitTime--
      that.getCodeBtnDisable = true
      this.codeBtnWord = `${this.waitTime}s  Post-retrieval `
      let timer = setInterval(function () {
        if (that.waitTime > 1) {
          that.waitTime--
          that.codeBtnWord = `${that.waitTime}s  Post-retrieval `
        } else {
          clearInterval(timer)
          that.codeBtnWord = ' Get verification code '
          that.getCodeBtnDisable = false
          // that.waitTime = 61
          that.waitTime = 2
        }
      }, 1000)
    },
    submitForm(formName) {
      const _this = this
      // Judge whether the input verification code is empty or not
      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(" I submitted it: ", par)
            //
            // const jwt = par.headers['authorization']
            // console.log(" I am token->", jwt)
            // const userInfo = par.data.data
            // console.log(" View user information =", userInfo)
            //
            // //  Share the data
            // _this.$store.commit("SET_TOKEN", jwt)
            // _this.$store.commit("SET_USERINFO", userInfo)
            //
            // //  Get
            // console.log(" I was acquired _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: ' Please enter an error ',
          type: 'error'
        });
      }
    }

  }

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

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