fix: 🐛 兼容字典下拉数据源和回显值类型不一致场景

Former-commit-id: 9823b72487
This commit is contained in:
hxr 2023-08-28 23:18:17 +08:00
parent a2c858ecca
commit 5fd62c26fe
2 changed files with 34 additions and 22 deletions

View File

@ -1,20 +1,18 @@
<template>
<div>
<el-select
v-model="selectedValue"
:placeholder="placeholder"
:disabled="disabled"
clearable
@change="handleChange"
>
<el-option
v-for="option in options"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</div>
<el-select
v-model="selectedValue"
:placeholder="placeholder"
:disabled="disabled"
clearable
@change="handleChange"
>
<el-option
v-for="option in options"
:key="option.value"
:label="option.label"
:value="option.value"
/>
</el-select>
</template>
<script setup lang="ts">
@ -29,8 +27,7 @@ const props = defineProps({
required: true,
},
modelValue: {
type: String,
default: "",
type: [String, Number],
},
placeholder: {
type: String,
@ -46,9 +43,24 @@ const emits = defineEmits(["update:modelValue"]); // 父组件监听事件,同
const options: Ref<OptionType[]> = ref([]); //
const selectedValue = computed(() => props.modelValue.toString()); // String
const selectedValue = ref<string | number | undefined>();
function handleChange(val?: string) {
watch([options, () => props.modelValue], ([newOptions, newModelValue]) => {
if (newOptions.length === 0) return; //
if (newModelValue == undefined) {
selectedValue.value = undefined;
return;
}
if (typeof newOptions[0].value === "number") {
selectedValue.value = Number(newModelValue);
} else if (typeof newOptions[0].value === "string") {
selectedValue.value = String(newModelValue);
} else {
selectedValue.value = newModelValue;
}
});
function handleChange(val?: string | number | undefined) {
emits("update:modelValue", val);
}

View File

@ -1,7 +1,7 @@
<!-- 字典组件示例 -->
<script setup lang="ts">
const stringValue = ref("1"); // (String)
const nmberValue = ref(1); // (Number)
const numberValue = ref(1); // (Number)
</script>
<template>
@ -22,7 +22,7 @@ const nmberValue = ref(1); // 性别(值为Number)
</el-form-item>
<el-form-item label="性别">
<dictionary v-model="nmberValue" type-code="gender" />
<dictionary v-model="numberValue" type-code="gender" />
<el-link :underline="false" type="success" class="ml-5"
>值为Number: const value = ref(1);
</el-link>