When a backend dataset does not follow the conventional { value, text } schema, the uni-data-select component requires custom mapping to correctly render options.
Approach 1: Transform Data on the Client Side
Remap incoming records into the expected shape before assigning them to the component.
import { ref } from 'vue';
const mappedOpts = [];
const selectedList = ref([]);
externalData.forEach(entry => {
mappedOpts.push({
value: entry.code,
text: entry.nameDisplay
});
});
selectedList.value = mappedOpts;
This ensures the component receives data in the { value, text } format it expects.
Approach 2: Extend Component with Configurable Keys
Modify the component source to accept custom property names for value and label fields via a configuration object, removing the need for preprocessing.
Add the new prop:
export default {
props: {
fieldMap: {
type: Object,
default: () => ({})
}
},
// ...other options
}
Template usage remains similar, but rendering uses dynamic keys:
<view
v-for="(opt, idx) in dataSource"
:key="idx"
@click="pick(opt)"
>
<text>{{ getItemLabel(opt) }}</text>
</view>
In the script, determine wich keys to use:
methods: {
getItemLabel(record) {
const { labelKey = 'text', valueKey = 'value' } = this.fieldMap;
if (this.formatTpl) {
let formatted = this.formatTpl;
formatted = formatted.replace(/\{([^}]+)\}/g, (_, k) => record[k] ?? '');
return formatted;
}
return record[labelKey] || `Unnamed`;
},
pick(record) {
const { valueKey = 'value' } = this.fieldMap;
const actualVal = record[valueKey];
this.$emit('change', actualVal);
this.updateDisplayText(this.getItemLabel(record));
},
updateDisplayText(txt) {
this.displayText = txt;
}
}
Initialize defaults during creation or when data arrives:
watch: {
dataSource: {
immediate: true,
handler(list) {
if (list.length) {
const { valueKey = 'value' } = this.fieldMap;
const match = list.find(it => it[valueKey] === this.modelValue);
this.updateDisplayText(match ? this.getItemLabel(match) : '');
}
}
}
}
Component Usage Example
<uni-data-select
v-model="chosenItem"
:fieldMap="customKeys"
:localdata="homeOptions"
@change="onSelection"
/>
const customKeys = {
labelKey: 'houseFullName',
valueKey: 'houseId'
};
const homeOptions = [
{ houseId: 101, houseFullName: 'Seaside Villa' },
{ houseId: 102, houseFullName: 'Mountain Cabin' }
];
function onSelection(id) {
console.log('Selected ID:', id);
}
This approach avoids manual data reshaping and supports arbitrary backend schemas.