The input box in the vue vant dialog pop-up box automatically gets focus

1. Background: Click Set Amount to pop up a pop-up box for setting the amount, requiring the input inside to automatically gain focus.

2. Using input's built-in autofocus="autofocus" can only automatically obtain focus when the pop-up window is called up for the first time. It will not get focus when the pop-up window is called up again without refreshing the page.

3. Solution: Give input autofocus="autofocus" and a ref attribute, and call the focus() method in the nextTick function callback. It must be called in this.$nextTick(function () {}); function callback, otherwise An error will be reported because the dom has not been obtained.

4. At this point, the Input inside the pop-up window will automatically gain focus every time.

 <common-dialog
            :showDialog="showAmount"
            :showConfirmButton="true"
            :confirmButtonText="'确定'"
            @confirm="setAmountConfirm"
        >
            <template #default>
                <input
                    autofocus="autofocus"
                    ref="getFocus"
                    type="number"
                    v-model="money"
                    class="set-amount-input"
                />
            </template>
        </common-dialog>
//设置金额弹窗
        showAmountPop() {
    
    
            this.showAmount = !this.showAmount;
            this.$nextTick(function () {
    
    
                this.$refs.getFocus.focus();
            });
        },

Insert image description here
This article is reprinted from this link, click here

Guess you like

Origin blog.csdn.net/qiaoqiaohong/article/details/118759815