Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value in vue- multiselect if i only have a property of options?

I have an option array which is shown in the multi-select options. But I need to select a default option which id is provided. In my code I need to select the default option which id = 2 . How to do that with multi-select in vue.js?

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/[email protected]"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vue-multiselect.min.css">

<div id="vue-app2">
    <div>
        <label class="typo__label">Single select / dropdown</label>
        <multiselect v-model="value" deselect-label="Can't remove this value" track-by="id" label="name"
            placeholder="Select one" :options="options" :searchable="false" :allow-empty="false">
            <template slot="singleLabel" slot-scope="{ option }"><strong>{{ option.name }}</strong> is written
                in<strong> {{ option.language }}</strong></template>
        </multiselect>
        <pre class="language-json"><code>{{ value  }}</code></pre>
    </div>
</div>
<script >
Vue.component('multiselect', window.VueMultiselect.default);

new Vue({
    el: '#vue-app2',
    data: {
        id:2,
        value:null,
        options: [
            { id:1, name: 'Vue.js', language: 'JavaScript' },
            { id:2, name: 'Rails', language: 'Ruby' },
            { id:3,name: 'Sinatra', language: 'Ruby' },
            { id:4,name: 'Laravel', language: 'PHP', $isDisabled: true },
            { id:5,name: 'Phoenix', language: 'Elixir' }
          ]
    }
});
</script>
like image 936
tuhin47 Avatar asked Oct 16 '19 04:10

tuhin47


1 Answers

If you need to take default value id from data then find and set default value on mounted;

new Vue({
  el: '#vue-app2',
  data: {
    id: 2,
    value: null,
    options: [
      { id: 1, name: 'Vue.js', language: 'JavaScript' },
      { id: 2, name: 'Rails', language: 'Ruby' },
      { id: 3, name: 'Sinatra', language: 'Ruby' },
      { id: 4, name: 'Laravel', language: 'PHP', $isDisabled: true },
      { id: 5, name: 'Phoenix', language: 'Elixir' }
    ]
  },
  mounted() {
    this.value = this.options.find(option => option.id === this.id);
  }
});
like image 185
Konrad Słotwiński Avatar answered Oct 08 '22 07:10

Konrad Słotwiński