Léo Coco
Léo Coco

Reputation: 4282

Multiple select and v-model with array of object

I'm using Vue.js 2.0 and the Element UI library.

I'm working with a multiple select component. The v-model property is here to pre-select any options. So if you have model: ['Option4'], the select will be preselected with Option4

I would like to be able to v-model an array of object instead of simply an array containing the label of each option.

That is to say instead of usingmodel: ['Option4'] I would like to be able to use something like model: [{name:'Option4'}, {name:'Option5'}].

When doing so the pre-selection is not made properly.

Is it possible to do that ? If so how ?

http://jsfiddle.net/3ra1jscx/

<div id="app">
<template>
  <el-select v-model="model" multiple placeholder="Select">
    <el-option v-for="item in options" :label="item.label" :value="item.value">
    </el-option>
  </el-select>
</template>
</div>

var Main = {
    data() {
      return {
        options: [{
          value: 1,
          label: 'Option1'
        }, {
          value: 2,
          label: 'Option2'
        }, {
          value: 3,
          label: 'Option3'
        }, {
          value: 4,
          label: 'Option4'
        }, {
          value: 5,
          label: 'Option5'
        }],
        model: ['Option4']
      }
    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

Upvotes: 3

Views: 5560

Answers (1)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

You should pass the value of object in options array.

var Main = {
  data() {
    return {
      options: [{
        value: 1,
        label: 'Option1'
      }, {
        value: 2,
        label: 'Option2'
      }, {
        value: 3,
        label: 'Option3'
      }, {
        value: 4,
        label: 'Option4'
      }, {
        value: 5,
        label: 'Option5'
      }],
      model: [4]
    }
  }
}

Here is working solution.

Upvotes: 1

Related Questions