Search code examples
javascriptvue.jsvuejs2ref

VueJs the input value doesnt cleared with the keypress ESC the first time


I want to clear the input when i press the ESC key, the bug that i've is when i press the ESC key the first time, the input isnt cleared but when i press ESC second time it is cleard

When i display in console the value of the input after first press, it's empty but not in the UI

Here is the small piece of code that ma,age the ESC Key :

Html :

<input
      type="text"
      :name="context.name"
      :id="context.id"
      v-model="context.model"
      @blur="context.blurHandler"
      @keyup="getSuggestions"
      autocomplete="no"
      class="mc-text-input"
      ref="autocompleteInput"
    />

And the ESC event :

case 27: {
          console.log('Before : ' + this.$refs.autocompleteInput.value)
          this.$refs.autocompleteInput.value = ''
          console.log('After : ' + this.$refs.autocompleteInput.value)
          this.resetAutocompleteElt() // hide the autocomplete list
          break
}

I need to force the first ESC press to clear this input


Solution

  • v-model uses two-way binding, so you should update context.model instead of trying to update the element value directly, as this is likely causing your problem.

    i.e. assuming you have access to context.model in your function that handles the event.

    Replace:

    this.$refs.autocompleteInput.value = ''
    

    with:

    this.context.model = '';