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

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

作者: 景阳冈大虫在此 | 来源:发表于2020-06-12 16:47 被阅读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>
    
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/mtkntktx.html