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>
Walking through your code,
:get-option-labelcalls the methodonSetOptionLabel(). This method emits an event containing theoptionvalue. Your parent component captures the event and callsupdateItemLabelmethod passing in that sameoptionvalue. 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.itemsto 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 toget-option-label, that's the method that needs to return a value for the labels to be set. So put all necessary logic in thatonSetOptionLabelmethod and remove the emit.