[Vuejs]-Vue.js showing div on input event deletes text from input

3👍

This is happening because localValue isn’t being updated by your input. When you start typing show will be set to true, so Vue will update the DOM to show your hidden div. But since localValue is null when the DOM updates your input will be blank since its value is bound to localValue. You can verify this by making handleInput toggle show‘s value instead of setting it to true and you’ll see that every time you type something in the input field the hidden div’s visibility will be toggled when the DOM updates but the input will be cleared ..

 methods: {
    handleInput(e) {
      this.show = !this.show;
    },
  }

So to solve this you’ll have to make sure that localValue is being updated by your input. The easiest way is to use v-model ..

<div id="app">
  <input id="foo"
       name="foo"
       v-model="localValue"
       type="text"
       placeholder=""
       autocomplete="off"
       @input="handleInput"
  >
  <div v-if="show">Testing</div>
</div>

JSFiddle

Alternatively you can manually handle the input in your handleInput method and set localValue to the typed value like Austio mentioned in his answer.

1👍

Hey so you are pretty close on this thought wise. When you handle input yourself, you have to set the new value when you have new input. In your specific case localValue will always be null which is not what i think you want. I think you are wanting something more like this.

 methods: {
    handleInput(e) {
      this.localValue = e.target.value;
      this.show = true;
    },
  }
👤Austio

Leave a comment