sagalbot / vue-select

Everything you wish the HTML <select> element could do, wrapped up into a lightweight, extensible Vue component.
https://vue-select.org
MIT License
4.62k stars 1.33k forks source link

Can't set selected option just using ID #1648

Closed jhob101 closed 2 years ago

jhob101 commented 2 years ago

Describe the bug

I store the select option as just the id. When the select is initialised I want to set the selected item using just the id.

Here's a simplified version of the code, the production version is more complicated as it involves a pinia store, which is why I'm not using v-model.

<template>
  <v-select
      placeholder="Select Accommodation..."
      :options="accommodations"
      :value="accommodationId"
      @option:selected="setAccommodationId"
      :reduce="(option) => option.id"
  ></v-select>
</template>
<script>
  import vSelect from 'vue-select';
  import 'vue-select/dist/vue-select.css';
  export default {
    data(): {
      return {
        accommodationId: 2,
        accommodations: [{id: 1, label: 'one'}, {id:2, label: 'two'}, {id:3, label:'three'}, {id:4, label:'four'}]
      }
    },
    methods: {
      setAccommodationId(selected) {
        this.accommodationId = selected.id;
      }
    }
  }
</script>

Now I have found that I can do this, which achieves what I want:

...
<v-select
    placeholder="Select Accommodation..."
    :options="accommodations"
    :modelValue="selectedAccommodation"
    @option:selected="setAccommodationId"
    :reduce="(option) => option.id"
></v-select>

...
selectedAccommodation() {
  return this.accommodations.filter(obj => {
    return obj.id === this.accommodationId
  })

But that feels like a bit of a hack.

I can't find a more generally supported way of doing this in the documentation. Am I missing something or does this feature not exist? If it doesn't exist then it seems like a bug as values would typically be stored as the id and so should be able to be set as just the id.

jhob101 commented 2 years ago

Closing as this should be in discussions.