一、开发背景

  • 产品出设计稿要求做一个仿原生app短信验证码组件,花了两小时搞出来一个还可以的组件,支持屏幕自适应,可以用于弹出框,或自己封装的vue组件里,希望可以帮助那些被产品压榨的同学,哈哈。?

  • 其核心思想就是利用一个输入框使用css3,translate属性,每输入一次后向右位移一个单位位置,直到输入完验证码个数消失。然后定义一个数组smsCodeList,初始化时push对象

smsCodeList = [{
    val: '',
    isError: ''
}]

二、费发不多说,先看演示

演示

H5仿原生app短信验证码vue2.0组件附源码地址

H5仿原生app短信验证码vue2.0组件附源码地址

三、代码解释

// html代码
<div class='sms-check-code-wrapper' @click='handleClick'>
 <div class="sms-code-container">
   <div :class="['sms-code-title', {'error': error}]"
        :style="{'color': error ? errorColor : errorColorDefault}">
   {{ title }}</div>
   <div class='sms-code-box'>
     <div class="sms-code-input-box" :style="{'transform': `translate(${inputBoxActive}%)`}">
       <input
           ref='refInout'
           v-show='isShowInputBox'
           type='number'
           v-model='inputValue'
           class='sms-code-input'
           :style="{
              'width': style.smsCodeItemWidth + '%',
              'paddingLeft': style.inputPL + '%'
            }"
           @keyup="onKeyUp"
           @keydown='onKeyDown'
           v-focus
           :maxlength='codeNum'
           autocomplete="one-time-code"
           inputmode="numeric"
           value=''
       />
     </div>
     <div class='sms-code-bottom flex-sb'>
       <div class='sms-code-item'
            :style="{
              'width': style.smsCodeItemWidth + '%'
            }"
            v-for='(item, index) in smsCodeList' :key='index'>
         <span :class="['sms-value', {'error': item.isError }]"
               :style="{'color': item.isError ? errorColor : errorColorDefault}">
         {{ item.val }}</span>
         <span :class="['sms-line', {'error': item.isError}]"
               :style="{'backgroundColor': item.isError ? errorColor : errorColorDefault}">
         </span>
       </div>
     </div>
   </div>
 </div>
</div>
只需简单的这几行html结构,用来渲染标题和输入框和验证码组件
js 代码也很简单
// 首先定义一些初始默认值,因为默认按照6位数验证码来的
let defaultCodeNum = 6
let defaultMoveUnit = 17.2
let defaultInputPL = 7
let defaultSmsCodeItemWidth = 14
export default {
  name: "VueSmsCheckCode",
  directives: {
    focus: {
      inserted: function (el) {
        el.focus()
      }
    }
  },
  props: {
    title: {
      type: String,
      default: '请录入验证码'
    },
    codeNum: { // 验证码个数
      type: Number,
      default: 6
    },
    isError: { // 验证码错误显示错误提示
      type: Boolean,
      default: false
    },
    errorColor: {
      type: String,
      default: '#D81A1A'
    }
  },
  data() {
    return {
      smsCodeList: [], // 验证码输入显示在div上的数字
      inputValue: '', // 输入框的值
      smsValue: '', // 验证码完毕后归总的变量
      moveUnit: 17.2, // input 位移单位
      inputBoxActive: 0, // 当前输入框位移位置
      currentIndex: 0, // 当前验证码索引
      isShowInputBox: true, // 是否显示输入框
      error: false, // 验证码错误报红
      errorColorDefault: '#b1b1b1', // 默认错误输入框颜色
      style: { // 默认样式
        inputPL: 0, // input padding-left值
        smsCodeItemWidth: 0, // 验证码显示item的宽度(自适应)
      }
    }
  },
  created() {
    this.reDomRender() // 初始化时,通过传过来的验证码个数重新渲染组件(各个dom位置,宽度等重新计算)
    this.compareList() // push 默认数据
    this.inputPaving() // 当点击手机验证码自动填充时,自动平铺数据
  },
  methods: {
    reDomRender() {
      this.style = {
        inputPL: Math.round(defaultCodeNum / (this.codeNum / defaultInputPL)),
        smsCodeItemWidth:  Math.round(defaultCodeNum / this.codeNum * defaultSmsCodeItemWidth)
      }
      this.moveUnit =  Math.round(defaultCodeNum / (this.codeNum / (defaultMoveUnit - .3333)))
    },
    compareList() {
      for (let i = 0; i < this.codeNum; i++) {
        if (this.smsCodeList.length < this.codeNum) {
          this.smsCodeList.push({
            val: '',
            isError: this.isError
          })
        }
      }
    },
    initAll() {
      this.smsCodeList = []
      this.compareList()
      this.inputValue = ''
      this.smsValue = ''
      this.inputBoxActive = 0
      this.currentIndex = 0
      this.isShowInputBox = true
      // 延时解决光标聚焦
      setTimeout(() => {
        this.$refs.refInout.focus()
      })
    },
    // 当点击验证码时,inputBoxActive,值要分铺在每个输入框里
    inputPaving() {
      let v = this.inputValue
      if (v.length > 0) {
        v.split('').forEach((item, index) => {
          if (index <= v.length) {
            this.smsCodeList[index].val = item
            const inputPosition = (index + 1) * this.moveUnit
            this.inputBoxActive = inputPosition >= 100 ? 100 : inputPosition
            this.currentIndex = index + 1
            this.smsValue += item
            this.inputValue = ''
            if (index + 1 === this.codeNum) {
              this.isShowInputBox = false
              this.sendFun()
            }
          }
        })
      }
    },
    onKeyDown(e) {
      let key = e.key;
      e.returnValue = !(key === 'e' || key === 'E' || key === '+' || key === '-');
    },
    onKeyUp(e) {
      if (this.currentIndex < 1) return
      if (e.code === 'Backspace' || e.key === 'Backspace') { // 会退
        this.currentIndex = this.currentIndex - 1
        this.inputBoxActive = this.inputBoxActive - this.moveUnit
        this.smsCodeList = this.smsCodeList.map((val, index) => {
          if (index === this.currentIndex) {
            val.val = ''
            val.isError = this.isError
            return val
          }
          return val
        })
      }
    },
    handleClick() {
      this.$refs.refInout.focus()
    },
    sendFun() {
      this.$emit('finish', this.smsValue)
    }
  },
  watch: {
    inputValue(v) { // 监听输入框输入的值
      if (!v) return
      // 初始化时,点击软键盘上的验证码自动填充时分铺input数据
      if (v.length > 1) {
        this.inputPaving()
        return;
      }
      this.inputBoxActive = this.inputBoxActive + this.moveUnit
      this.smsCodeList.map((val, index) => {
        if (this.currentIndex === index) {
          if(val) {
              //当前输入的位置使红色底部条初始化
            val.isError = false
          }
          val.val = v
          return val
        }
        return val
      })
      this.currentIndex += 1
      this.inputValue = ''
      if (this.currentIndex >= this.codeNum) { // 当最后一位时发
        this.isShowInputBox = false
        this.smsCodeList.forEach(val => {
          this.smsValue += val.val
        })
        this.sendFun()
      }
    },
    isError(v) { // 监听验证码是否错误
      this.error = v
      if (v) {
        this.smsCodeList.map(value => {
          value.isError = true
          return value
        })
        this.initAll()
      }
    }
  }
}
剩下的就是css了
npm install vue-sms-check-code --save
最新版1.0.1 (2022/5/25)
包常规操作下载使用
另外需要完整的代码请到github或gitee上下载
开源并总结整理真的很费时间,如果不错还请star
?️问题请issues

gitee源码地址

github源码地址

源码里有example 使用方式,使用灰常简单。

开源并总结整理真的很费时间,欢迎star

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。