Getting option label via $emit

147 Views Asked by At

I'm using vue-select as my dropdown. Vue-select has a prop called getOptionLabel to return a property from an object. I have a component where I pass a method to to get the code from the option object and I emit the method from my created component but the label is not showing. Please help me.

This what I've tried:

<dropdown-items
    name="item"
    :labelElement="$t('fields.item')"
    :keyElement="'item-field'"
    :item_id="itemReceiveItem.item_id"
    :options="items"
    @setOptionLabel="updateItemLabel"
    @selectItem="
        (event) =>
            updateItem({
                key: itemReceiveItem.id,
                item_id: event.id,
                attr: 'item_id',
            })
    "
    @clearSelected="
        clearSelectedItem({
            key: itemReceiveItem.id,
            item_id: itemReceiveItem.item_id,
            attr: 'item_id',
        })
    "
    @activeField="activeField"
/> 

updateItemLabel(option) {
    if (typeof option === 'object') return option.code;

    const optionObject = this.lists.items.find(
        (item) => item.id.toString() === option.toString()
    );

    if (optionObject) return optionObject.code;

    return option;
},

DropdownItem.vue

<v-select
    :name="name"
    :key="keyElement"
    :value="item_id"
    :options="options"
    :clearable="false"
    :get-option-label="onSetOptionLabel"
    :disabled="item_id ? true : false"
    @input="onSelectItem($event)"
/>

<script>
export default {
  emits: ['selectItem', 'clearSelected', 'setOptionLabel'],
  methods: {
    onSetOptionLabel(option) {
      this.$emit('setOptionLabel', option);
    },
  },
};
</script>
1

There are 1 best solutions below

0
yoduh On

Walking through your code, :get-option-label calls the method onSetOptionLabel(). This method emits an event containing the option value. Your parent component captures the event and calls updateItemLabel method passing in that same option value. This parent method performs some logic and returns a value... where is the value returned? It's not to the v-select, that's down in the child component. The answer is nowhere.

There are a few ways you could solve your problem but in my opinion you should pass down this.lists.items to DropdownItem.vue as an additional prop and perform all the necessary label logic within that component to keep things as simple as possible. Whatever method you assign to get-option-label, that's the method that needs to return a value for the labels to be set. So put all necessary logic in that onSetOptionLabel method and remove the emit.