Search code examples
javascripthtmlvue.jsvuexonfocus

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!


Solution

  • 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()