如果我只有 属性 个选项,如何在 vue- multiselect 中设置默认值?

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

我有一个选项数组,显示在 multi-select 选项中。但是我需要 select 一个提供了 id 的默认选项。在我的代码中,我需要 select 默认选项 which id = 2 。如何使用 multi-select in vue.js?

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vue-multiselect@2.1.0"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/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>

如果您需要从 data 中获取默认值 id,则在 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);
  }
});