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

2019-11-14  本文已影响0人  AR7_

前言

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

功能需求

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

代码实现

<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>

上一篇 下一篇

猜你喜欢

热点阅读