Home > OS >  Binding v-model in vue multiselect and creating an object based on it in a list
Binding v-model in vue multiselect and creating an object based on it in a list

Time:11-15

Trying to create a dynamically generated list of objects using prime vue and multiselect. A simple v-model binded to a variable creates a list of selected options.

<MultiSelect v-model="selected_signals" optionLabel="name" optionValue="name" :options="simu_signals" />

Output of let's say 3 signals is:

selected_signals = ['signal1', 'signal2', 'signal3']

What I need is to generate, each time an option is selected, an object with the default configuration of the selected signal. So same output of those 3 signals which i need should be:

selected_signals = [{
    name: 'signal1',
    interpolation: true,
    unit: '',
    type: 'origin'
},
{
    name: 'signal2',
    interpolation: true,
    unit: '',
    type: 'origin'
},
{
    name: 'signal3',
    interpolation: true,
    unit: '',
    type: 'origin'
},
]

Struggling with that hardly, I tried to listen to @change event and then create the structure, but in this case Multiselect is not binded to any values so I can't delete them from list and etc.

CodePudding user response:

There is @input event for vue-multiselect, but you don't really need it for this usecase.

Check the below working example where I have removed optionValue

var app = new Vue({
  el: '#app',
  components: { Multiselect: window.VueMultiselect.default },
  data () {
    return {
      selectedSignals: [],
      options: [{
       name: 'signal1',
       interpolation: true,
       unit: '',
       type: 'origin'
      },
      {
       name: 'signal2',
       interpolation: true,
       unit: '',
       type: 'origin'
      },
      {
       name: 'signal3',
       interpolation: true,
       unit: '',
       type: 'origin'
      },
     ],
    }
  },
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/[email protected]"></script>
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vue-multiselect.min.css">
  <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js"></script>
<div id="app">
<div>
  <multiselect
    v-model="selectedSignals"
    track-by="name"
    placeholder="Select signal"
    label="name"
    :options="options"
    :multiple="true"
    :close-on-select="false"
  >
  </multiselect>
</div>
<pre ><code>{{ JSON.stringify(selectedSignals) }}</code></pre>
</div>

  • Related