I'm using select
with v-model
and have options with v-for
and object as a value. Options are some elements identified by id. How do I make option preselected based on custom equality (in this case by equal id
field)? I'm looking for something similar to angularjs' track by
from ng-options
.
https://jsfiddle.net/79wsf1n4/5/
How to make the input preselected with the value with equal id?
template:
<div id="vue-instance">
<select v-model="selected">
<option v-for="item in inventory" :value="item" :key="item.id">
{{ item.name }}
</option>
</select>
<p>
{{ selected.id }}
</p>
</div>
js:
var vm = new Vue({
el: '#vue-instance',
data: {
inventory: [
{name: 'MacBook Air', id: 1},
{name: 'MacBook Pro', id: 2},
{name: 'Lenovo W530', id: 3},
{name: 'Acer Aspire One', id: 4}
],
selected: {
id: 2
}
}
});
You could add the selected attribute as per Dharmendra's answer.
The issue however is that you're not assigning a valid object to your selected property. Vue will try to look for an identical object in your option list, it will do this by object equality comparison.
At this time I'm not aware whether it's possible to tell Vue to base the initial selection on an attribute, however a very simple solution is to assign the selected property based on the ID yourself in the created lifecycle callback:
var vm = new Vue({
el: '#vue-instance',
data: {
inventory: [
{name: 'MacBook Air', id: 1},
{name: 'MacBook Pro', id: 2},
{name: 'Lenovo W530', id: 3},
{name: 'Acer Aspire One', id: 4}
],
selected: 2
},
created: function() {
this.selected = this.inventory.find(i => i.id === this.selected);
}
});
I've updated your Fiddle as well.
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