超简洁!vue实现自动聚焦下一个输入框(验证码常用)

2020-06-12  本文已影响0人  景阳冈大虫在此
效果
 <num-inputs v-model="mesVal"></num-inputs>
// script
data(){
    return{
      mesVal:null
    }
}
<template>
    <div class="numInputs">
        <input
            v-for="(n, index) in amount"
            v-model="arr[index]"
            maxlength="1"
            @keydown="nextFocus($event, index)"
            ref="numInput"
            type="tel"
        />
    </div>
</template>
<script>
export default {
    props: {
        amount: {
            default: 6,
            type: Number
        }
    },
    data() {
        return {
            arr: []
        };
    },
    created() {
        setTimeout(() => {
            this.$refs.numInput[0] && this.$refs.numInput[0].focus();
        }, 0);
    },
    watch: {
        arr(val) {
            this.$emit('input', val.join(''));
        }
    },
    methods: {
        nextFocus($event, index) {
            // 键入时光标跳转
            this.arr[index] &&
                this.$refs.numInput[index + 1] &&
                this.$refs.numInput[index + 1].focus();
            // 删除
            if ($event.keyCode === 8) {
                if (this.arr[index]) {
                    this.arr[index] = '';
                    this.arr = JSON.parse(JSON.stringify(this.arr));
                    this.$refs.numInput[index].focus();
                } else {
                    this.$refs.numInput[index - 1] &&
                        this.$refs.numInput[index - 1].focus();
                }
            }
        }
    }
};
</script>
<style lang="scss">
.numInputs {
    margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    input {
        width: 40px;
        border-bottom: 1px solid rgba(221, 221, 221, 1);
        font-size: 18px;
        color: #2b293a;
        line-height: 21px;
        text-align: center;
    }
}
</style>

上一篇下一篇

猜你喜欢

热点阅读