Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue preselect value with select, v-for, and v-model

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
    }
  }
});
like image 665
Tuan Pham Avatar asked Apr 12 '17 10:04

Tuan Pham


1 Answers

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.

like image 72
thomaux Avatar answered Nov 14 '22 23:11

thomaux