Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus on an input that is located inside another component in vuejs?

I would like to be able to focus on input field when certain keys are entered. The input I would like to focus on exists inside autocomplete-vue. This is where I call it:

<autocomplete v-shortkey="['alt', 's']"
              @shortkey.native="theAction()"
              ref="autocompleteInput" 
></autocomplete>

theAction method which I would like to allow me to focus on the input, looks like this:

theAction () {
      this.$refs.autocompleteInput.$el.focus()
    }

this focus on the whole section which is not what I want. the input exists 2 divs inside the what theAction focuses on. For bettere perspective, this is what this.$refs.autocompleteInput.$el returns :

<div>
  <div data-position="below" class="autocomplete"> 
     <input role="combobox" class="autocomplete-input"> 
  </div>
</div>

Any ideas on how I can focus on the input with class autocomplete-input? any suggestion is helpful!

like image 699
Shinwi Avatar asked Oct 23 '25 19:10

Shinwi


1 Answers

Add a ref in the autocomplete component for the <input> and add a method to focus it

<input role="combobox" class="autocomplete-input" ref="input"> 
methods: {
  focus() {
    this.$refs.input.focus()
  }
}

You can then call it from the parent component like this

this.$refs.autocompleteInput.focus()
like image 126
Phil Avatar answered Oct 26 '25 08:10

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!