How can I set a preselected option in a select
element using v-model
, v-for
for options, and an object as the value? The options are elements with unique ids, and I want to preselect based on custom equality (e.g., matching the id field). Is there a way to achieve this similar to AngularJS' track by
feature in ng-options
?
https://jsfiddle.net/79wsf1n4/5/
What's the best approach to preselect the input with the value that has an 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>
JavaScript:
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
}
}
});