Goteii
Goteii

Reputation: 170

v-model for array of objects as props

I pass v-model as props with array of objects, while clicking on one or more options in my select I want to get the whole object as a value.

//select.vue
<template>
    <select
  class="filter__select"
  multiple="true"
  :value="value"
  @input="$emit('input', $event.target.value)"
>
  <option
    class="filter__option"
    v-for="item in options"
    :value="item"
    :key="item.id"
  >
    {{ item.name }}
  </option>
</select>
</template>

<script lang="ts">
.....
  @Prop({ required: true, type: Array }) options!: ContinentI[] | CountryI[];
  @Prop({ required: true, type: Array }) value!: ContinentI[] | CountryI[];
......
</script>

//filters.vue
.......
<Select :options="continentsList" v-model="multipleContinents"
    >Continents</Select>
........

When I click on one of more options I get [object Object] in console and my mapping function gets messed because of "continents.map is not a function" which worked before trying to pass it as props. How can I properly get the whole object in @input?

Upvotes: 0

Views: 1111

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

the option value attribute accepts a number or string not object so you should bind it to the id then when you emit the selected value you should find the correspondant object :

    <select
  class="filter__select"
  multiple="true"
  :value="value"
  @input="$emit('input', options.find(option=>option.id === $event.target.value))"
>
  <option
    class="filter__option"
    v-for="item in options"
    :value="item.id"
    :key="item.id"
  >
    {{ item.name }}
  </option>

Upvotes: 1

Related Questions