InputGroup.vue 2.13 KB
<template>
  <div class="input-group">
    <template v-for="(i,index) in length">
      <div
        :key="index"
        :class="['input',{'active':values[index]},{'error':error}]"
      >
        <input
          v-model="values[index]"
          type="number"
          maxlength="1"
          @input="input(index,$event)"
          :ref="`focus-${index}`"
          @keydown="keydown(index,$event)"
        >
      </div>
    </template>
  </div>
</template>

<script type='text/ecmascript-6'>
export default {
  name: 'InputGroup',
  data () {
    return {
      values: [],
      flag: false,
      focusList: []
    }
  },
  props: {
    length: {
      type: Number,
      default: 6
    },
    value: {
      type: String,
      default: ''
    },
    error: {
      type: Boolean,
      default: false
    },
    pattern: {
      type: RegExp
    }
  },
  watch: {
    'values' (newVal) {
      this.$emit('input', newVal.join(''))
    },
  },
  mounted () {
    let { value, length } = this
    if (value) {
      value = value.substring(0, length)
      this.values = value.split('')
    } else {
      this.values = new Array(6).fill('')
      this.focusList = new Array(6).fill(false)
    }
  },
  methods: {
    keydown (index, $event) {
      let { keyCode } = $event
      if (keyCode == 8) {
        setTimeout(() => {
          if (index > 0) this.$refs[`focus-${index - 1}`][0].focus()
        }, 100)
      }
    },
    input (index) {
      let { length, pattern } = this
      this.values[index] = pattern.test(this.values[index]) ? this.values[index].substring(0, 1) : ''

      if (index < length - 1 && this.values[index]) this.$refs[`focus-${index + 1}`][0].focus()
    }
  }
}
</script>

<style scoped lang='scss'>
.input-group {
  display: flex;
  .input {
    width: 36px;
    height: 36px;
    background: #ffffff;
    border: 1px solid #dbdbdb;
    padding: 0 12px;
    box-sizing: border-box;
    margin-right: 24px;
    input {
      width: 100%;
      height: 100%;
      border: none;
    }
    &:last-of-type {
      margin-right: 0;
    }
  }
  .active {
    border-color: #008fff;
  }
  .error {
    border-color: #fa5151;
  }
}
</style>