Vue <input>标签 实现六格验证码输入框

前言

现在的需求就是要实现一个六格验证码输入框,本来想直接在网上找现成的轮子的,但是找了一圈没发现可以让我满意的,那就试着自己摸索了。

功能需求

其实,除了样式需要处理,主要是有以下三点需求:

  • 只支持纯数字输入,我们知道如果input设置typenumber时,其实是可以输入自然常数e这个英文字母的,而且对于处理这种纯数字输入,如果处理不当,在中文模式下打出拼音,这时切换中英文经常出现输入了英文字母的现象。
  • 在前一个输入框输入完成,光标自动移动至下一个输入框。
  • 按下BackSpace键,清空当前输入框内容,光标自动移动至上一个输入框。

代码实现

<template>
  <div class="six-digit-wrapper">
    <input v-for="(item,index) in digits"
           :key="index"
           :ref="`ref${index}`"
           class="input"
           v-model="item.value"
           type="text"
           oninput="value=value.replace(/[^\d]/g,'')"
           @input="onInput(index)"
           @keyup.delete="onDelete(index)"
           maxlength="1" />
  </div>
</template>
<script>
export default {
  data () {
    return {
      digits: [
        {
          value: ''
        },
        {
          value: ''
        },
        {
          value: ''
        },
        {
          value: ''
        },
        {
          value: ''
        },
        {
          value: ''
        }
      ]
    }
  },
  methods: {
    onInput (index) {
      // index < 5 ,如果是第6格,不触发光标移动至下一个输入框。
      if (this.digits[index].value && index < 5) {
        this.$refs['ref' + (index + 1)][0].focus()
      }
    },
    onDelete (index) {
      // 如果是第1格,不触发光标移动至上一个输入框
      if (index > 0) {
        this.$refs['ref' + (index - 1)][0].focus()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.six-digit-wrapper {
  display: flex;
  flex-direction: row;
  .input {
    display: flex;
    width: 25px;
    margin-left: 10px;
    height: 44px;
    font-size: 18px;
    color: #333333;
    background-color: #f2f2f2;
    text-align: center;
    outline: none; // 去除选中状态边框
    border: solid 1px #d2d2d2;
    border-top: 0px;
    border-left: 0px;
    border-right: 0px;
  }
}
</style>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容