I have two <select>
elements. When I select a value in the first, I want to default the value for the second. It works with v-model
, but not with :value
.
一个是车辆清单。
<select :value="vehicle" @change="setVehicle($event.target.value)">
<option value="CAR">Car</option>
<option value="PLANE">Plane</option>
</select>
The other is a list of parts. The WINGS
part is only visible if PLANE
is selected.
<select :value="part" @change="setPart($event.target.value)">
<option value="ENGINE">Engine</option>
<option value="WINDOWS">Wheels</option>
<option v-if="vehicle === 'PLANE'" value="WINGS">Wings</option>
</select>
The setter for vehicle is trivial, but the default part for a plane is the conditionally rendered WINGS
.
setVehicle: function(newVehicle) {
this.vehicle = newVehicle;
if (this.vehicle === "PLANE") {
this.part = "WINGS";
} else {
this.part = "ENGINE";
}
}
The reactive part
data is set to the correct value, e.g. you can display it with {{ part }}
, but the <select>
element is not properly updated. If I change the part's select to use v-model it works fine:
<select v-model="part">
Using v-model is not an acceptable workaround because in my real world app the part
is readonly and can only be mutated with a setter (using a store-like architecture). Another workaround is using a setTimeout(.., 1)
in the setVehicle setter. I really do not like that solution. What I really would like to know is why v-model
behaves differently than :value/@change
when the documentation suggest v-model
is simply syntactic sugar.
Demo: https://codesandbox.io/s/eager-liskov-2yor4?file=/src/App.vue