The :selected
prop is not selecting the target option
in Vue2 when i use v-model
for select
:
Template
...
<select v-model="form.item">
<option :value="item.id" v-for="(item, index) in items" :selected="item.status == 2">{{ item.name }}</option>
</select>
...
Script
data: function () {
return {
items: [{id:1, name: "foo", status: 1},{id: 3, name: "bar", status: 2}],
form: {item: null}
}
}
In this case , after mounted there is no selected option.
How can i fix this?
Note
When i remove v-model
it works fine (target option
is selected by default) but i don't have the value of the selected option
in form.item
In 2.2 we introduced the model component option that allows the component to customize the prop and event to use for v-model . However, this still only allowed a single v-model to be used on the component.
We can get the selected option on change with Vue. js by setting @change to a method. We set v-model to the key reactive property bind the selected value attribute value to key . And we set @change to onChange($event) to call onChange with the change event object.
To specify the type of prop you want to use in Vue, you will use an object instead of an array. You'll use the name of the property as the key of each property, and the type as the value. If the type of the data passed does not match the prop type, Vue sends an alert (in development mode) in the console with a warning.
v-model will ignore the initial value, checked or selected attributes. found on any form elements
The solution is to remove :selected binding. and use data props to bind to v-model
<select v-model="form.selectedItem">
<option :value="item.id" v-for="(item, index) in items">{{ item.name }}
</option>
</select>
declare vue instance as
data() {
return {
selectedItem: 2
}
}
link to official documentation
Another solution is by using $refs
instead of v-model.
<select ref="selectedItem">
<option v-for="(item, index) in items" :value="item.id" :selected="item.status == 2">
{{ item.name }}
</option>
</select>
Then to get the value of the selected item, call...
this.$refs.selectedItem.value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With