首先,目的是可以实现默认选中el-option的选项,并且选中后返回的value是对象,用于传到后端,所以要加value-key,el-option的value也需要写为对象
<el-select v-model="productName" filterable clearable placeholder="请选择" @change="selectProduct" value-key="productCode">
<el-option
v-for="(data, index) in productList"
:label="data.productName"
:value="data"
:key="data.productCode"
></el-option>
</el-select>
const emit = defineEmits<{
(e: 'change', value: string): void
(e: 'update:modelValue', value: string): void
}>()
const props = defineProps({
modelValue: [Number, String, Object, Array],
});
const productList:any = ref([])
const productCode = ref('')
const productName = ref('')
监听父组件传入默认值进行赋值,选项修改后传出事件
watchEffect(() => {
emit("update:modelValue", productCode.value);
})
watchEffect(() => {
if(props.modelValue) {
productCode.value = props.modelValue + ''
} else {
productCode.value = ''
}
})
const selectProduct = (val:any) => {
productName.value = val.productName
emit("update:modelValue", val.productCode);
emit("change", val);
}
这时默认选项的样式没有变为蓝色,如果value改成不为对象,样式才能正常显示