diff --git a/packages/components/select-v2/__tests__/select.test.ts b/packages/components/select-v2/__tests__/select.test.ts index 629771fe5d..c4aaced1e4 100644 --- a/packages/components/select-v2/__tests__/select.test.ts +++ b/packages/components/select-v2/__tests__/select.test.ts @@ -1268,6 +1268,65 @@ describe('Select', () => { expect(placeholder.text()).toBe('option 2') }) + it('not options keep the selected label', async () => { + const initial = [ + { + value: '1', + label: 'option 1', + }, + { + value: '2', + label: 'option 2', + }, + ] + + const wrapper = createSelect({ + data() { + return { + value: '1', + options: [...initial], + } + }, + + methods: { + handleSearch(value) { + this.options = initial.filter((item) => item.label.includes(value)) + }, + }, + }) + + await nextTick() + + const select = wrapper.findComponent(Select) + const selectVm = select.vm as any + const vm = wrapper.vm as any + + expect(selectVm.selectedLabel).toBe('option 1') + + const trigger = wrapper.find(`.${WRAPPER_CLASS_NAME}`) + + await trigger.trigger('mouseenter') + await trigger.trigger('click') + + vm.handleSearch('2') + await nextTick() + expect(wrapper.vm.options.length).toBe(1) + expect(selectVm.selectedLabel).toBe('option 1') + + vm.handleSearch('3') + await nextTick() + expect(wrapper.vm.options.length).toBe(0) + expect(selectVm.selectedLabel).toBe('option 1') + + vm.value = '3' + await nextTick() + expect(selectVm.selectedLabel).toBe('3') + + vm.value = '' + await nextTick() + expect(selectVm.selectedLabel).toBe('') + }) + it('default value is null or undefined', async () => { const wrapper = createSelect({ data() { diff --git a/packages/components/select-v2/src/useSelect.ts b/packages/components/select-v2/src/useSelect.ts index 046ad578e7..7b8c0bb9b6 100644 --- a/packages/components/select-v2/src/useSelect.ts +++ b/packages/components/select-v2/src/useSelect.ts @@ -754,7 +754,7 @@ const useSelect = (props: ISelectV2Props, emit: SelectEmitFn) => { } } - const initStates = () => { + const initStates = (needUpdateSelectedLabel = false) => { if (props.multiple) { if ((props.modelValue as Array).length > 0) { const cachedOptions = states.cachedOptions.slice() @@ -780,7 +780,9 @@ const useSelect = (props: ISelectV2Props, emit: SelectEmitFn) => { if (~selectedItemIndex) { states.selectedLabel = getLabel(options[selectedItemIndex]) } else { - states.selectedLabel = getValueKey(props.modelValue) + if (!states.selectedLabel || needUpdateSelectedLabel) { + states.selectedLabel = getValueKey(props.modelValue) + } } } else { states.selectedLabel = '' @@ -816,7 +818,7 @@ const useSelect = (props: ISelectV2Props, emit: SelectEmitFn) => { (!props.multiple && getValueKey(val) !== getValueKey(states.previousValue)) ) { - initStates() + initStates(true) } if (!isEqual(val, oldVal) && props.validateEvent) { elFormItem?.validate?.('change').catch((err) => debugWarn(err))