Aamir
Aamir

Reputation: 101

Unexpected select dropdown behaviour with vue.js

If I remove background-green class binding or value binding from the select element then it works as a normal dropdown. But let's say I didn't remove the background-green class binding then after selecting, the selected option is not displayed but if I select again the same selected option or other option then it would be displayed. Same behavior with value binding. So why it's working second time? This is my real concern/confusion.

Here is the link of running example with sample code.

Upvotes: 1

Views: 468

Answers (1)

Matt
Matt

Reputation: 44078

The problem is a mixture of :value="defaultValue" not actually changing (because defaultValue never changes) and also a side effect of a rerender happening the first time.

Since :value is essentially always "", any time the <select> is re-rendered, Vue sets the value to that empty string.

You have handleInput set fillBg = true which triggers a re-render, because background-green was not in the initial render. This means Vue will reset the value of the <select> back to defaultValue (blank)

During the time it appears to work after the first selection, what's actually happening is DOM local state showing what you selected. Since there is no change to the vdom (background-green is already there), Vue is not re-rendering and thus not resetting the value.

The proper way to fix this is to either update defaultValue (perhaps rename this) during the input event or use v-model. The point is to have Vue set the proper value any time it renders.

handleInput(e) {
  this.fillBg = true;
  this.defaultValue = e.target.value;
},

Upvotes: 3

Related Questions