Search code examples
javascriptvue.jsfocusvuejs3

How do I keep the focus on an input, after i click on a button without flickering in Vue 3?


Script

const amountRef = ref(null);
const amount = ref(0.1);

const insertSuggestion = (e, value) => {
  e.preventDefault();
  e.stopPropagation();
  amount.value = value;
  amountRef.value.focus();
};

Template

<Suggestion
   class="..."
   v-for="suggestion in suggestions"
   :key="suggestion"
   @click="insertSuggestion($event, suggestion)"
>
    {{ suggestion }}
</Suggestion>
<input
   class="..."
   @keyup.enter="handleBuy"
   placeholder="Amount"
   ref="amountRef"
   v-model="amount"
/>

enter image description here


Solution

  • You can re-focus the input element on the blur event:

    <input ref="amountRef" @blur="$refs.amountRef.focus()"/>
    

    Edit

    You also need to check the relatedTarget of the blur event to make sure you only re-focus when one of the buttons is clicked.

    Note: this solution does not work on Firefox.

    <Suggestion
       class="suggestion-btn"
       ...
    >
    </Suggestion>
    <input
       ref="amountRef"
       @blur="onBlur"
    />
    
    
    onBlur(evt) {
        if (
            evt.relatedTarget &&
            evt.relatedTarget.classList.contains("suggestion-btn")
        ) {
            this.$refs.amountRef.focus();
        }
    },