Coderz9
Coderz9

Reputation: 173

Vue default selected option on object

I know that the v-model data should be the same as the default option but what I do when I have things setup like this:

data: function() {
    return {
      user: {
        usertype: {},
    }
}

<select v-model="user.usertype" class="btn btn-secondary d-flex header-input">
<option
v-for="(usertype, index) in usertypes"
:key="index"
:value="{value: usertype['short_desc_'+locale], max_user: usertype['max_user']}"
>{{usertype['short_desc_'+locale]}}</option>

I tried adding another option disabled value="" but it didn't select it as default. more like, it doesn't show. when I open up the dropdown menu, the first item is checked already but it does not show when its closed. any help is appreciated :)

Edit: Structure of usertypes

[{"id":1,"short_desc_de":"Mann","short_desc_en":"Men","min_user":1,"max_user":1,"created_at":"2019-09-19 08:07:06","updated_at":"2019-09-19 08:07:06"},{"id":2,"short_desc_de":"Frau","short_desc_en":"Woman","min_user":1,"max_user":1,"created_at":"2019-09-19 08:07:06","updated_at":"2019-09-19 08:07:06"},...]

Upvotes: 1

Views: 72

Answers (1)

Sarah Gro&#223;
Sarah Gro&#223;

Reputation: 10879

Your approach of adding an additional <option> element was good, but instead of setting value="", you need to match the default state of user.usertype, which is an empty object. So if you set the attribute :value="{}", you'll get the desired result.

(on a sidenote unrelated to the technics, your first usertype should probably be "Man" instead of plural "Men" in English, or maybe you'd be even better of with "male"/"female")

new Vue({
  el: '#app',
  data: {
    user: {
      usertype: {}
    },
    usertypes: [{"id":1,"short_desc_de":"Mann","short_desc_en":"Men","min_user":1,"max_user":1,"created_at":"2019-09-19 08:07:06","updated_at":"2019-09-19 08:07:06"},{"id":2,"short_desc_de":"Frau","short_desc_en":"Woman","min_user":1,"max_user":1,"created_at":"2019-09-19 08:07:06","updated_at":"2019-09-19 08:07:06"}],
    locale: 'en'
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <select v-model="user.usertype" class="btn btn-secondary d-flex header-input">
  <option v-if="!Object.keys(user.usertype).length" :value="{}" disabled>please choose one</option>
  <option
  v-for="(usertype, index) in usertypes"
  :key="index"
  :value="{value: usertype['short_desc_'+locale], max_user: usertype['max_user']}"
  >{{usertype['short_desc_'+locale]}}</option>
  </select>
  <p>{{user.usertype}}</p>
</div>

Upvotes: 2

Related Questions