- 需求描述: 接口返回的当前数据在预设的option列表中不存在的情况下, el-select中的值会显示为当前接收的值. 需要显示为指定的label
<el-select
style="width: 300px"
v-model="selectValue">
<el-option
v-for="item in options2"
:key="item.id"
:value="item.value"
:label="item.label" />
<template #label="{ value }">
{{ transLabel(value) }}
</template>
</el-select>
const options2 = ref([
{ id: 11, value: 11, label: '十一' },
{ id: 12, value: 12, label: '十二' }
])
const selectValue = ref(88)
function transLabel(val: number) {
// 1. 在数据中找到对应的label
const oOption = options2.value.find(option => option.value === val)
if (oOption) {
return oOption.label + '_' // 验证#label与:label自定义属性的优先级, 结论是#label优先级会更高, 会直接覆盖掉:label自定义属性的值
} else {
return '未知数据:' + val
}
}
- template#label优先级会更高, 会直接覆盖掉:label自定义属性的值