I am currently developing a customizable Select component that can be used with any Array provided as options.
It is working well when the object properties in the array have the same names bound in the component. However, if an array of objects with different property/attribute names is passed, the options do not render as expected. Is there a way to specify on the component which object property should be used as the option value and which as the option label?
FormSelect.vue / Component
<template>
<select :id="id" v-model="selected">
<option v-if="options.length > 0" value="">Please Select</option>
<option
v-if="options.length > 0"
v-for="(option, index) in options"
:key="index"
:selected="selected"
:value="option.value"
v-text="option.name"
/>
</select>
</template>
<script>
props: {
value: {
type: [Array, String, Number, Object],
default: null
},
options: {
type: Array,
default: () => []
}
},
computed: {
selected: {
get() {
return this.value ? this.value : "";
},
set(v) {
this.$emit("input", v);
}
}
}
</script>
Parent.vue / Parent
<form-select
id="gender"
label="Gender"
:options="genderOptions"
@input="handleEdit(deep(profile))"
v-model="user.gender"
/>
This works:
genderOptions: [
{ name: "Male", value: "MALE" },
{ name: "Female", value: "FEMALE" }
],
This would not work (notice the object key names):
genderOptions: [
{ id: "Male", gender: "MALE" },
{ id: "Female", gender: "FEMALE" }
],
Therefore, there is a need to indicate to the component which properties should be used as the option value and label. It could be something like this, but it would also need to be handled on the component side:
<form-select
id="gender"
label="Gender"
:options="genderOptions"
optionVal="gender"
optionName="id"
@input="handleEdit(deep(profile))"
v-model="user.gender"
/>