diff --git a/packages/vant/src/date-picker/DatePicker.tsx b/packages/vant/src/date-picker/DatePicker.tsx index 9bebb67bf..52334556f 100644 --- a/packages/vant/src/date-picker/DatePicker.tsx +++ b/packages/vant/src/date-picker/DatePicker.tsx @@ -53,6 +53,7 @@ export default defineComponent({ setup(props, { emit, slots }) { const currentValues = ref(props.modelValue); + const updatedByExternalSources = ref(false); const genYearOptions = () => { const minYear = props.minDate.getFullYear(); @@ -76,7 +77,9 @@ export default defineComponent({ const getValue = (type: DatePickerColumnType) => { const { minDate, columnsType } = props; const index = columnsType.indexOf(type); - const value = currentValues.value[index]; + const value = updatedByExternalSources.value + ? props.modelValue[index] + : currentValues.value[index]; if (value) { return +value; } @@ -146,11 +149,16 @@ export default defineComponent({ watch( () => props.modelValue, - (newValues) => { + (newValues, oldValues) => { + updatedByExternalSources.value = isSameValue( + oldValues, + currentValues.value + ); newValues = formatValueRange(newValues, columns.value); if (!isSameValue(newValues, currentValues.value)) { currentValues.value = newValues; } + updatedByExternalSources.value = false; }, { immediate: true, diff --git a/packages/vant/src/date-picker/test/index.spec.ts b/packages/vant/src/date-picker/test/index.spec.ts index b26846dab..af160de78 100644 --- a/packages/vant/src/date-picker/test/index.spec.ts +++ b/packages/vant/src/date-picker/test/index.spec.ts @@ -200,3 +200,24 @@ test('should update value correctly when dynamically change min-date', async () wrapper.emitted<[PickerConfirmEventParams]>('confirm')![0][0].selectedValues ).toEqual(['2020', '12', '20']); }); + +test('should be displayed correctly when modelValue updated by external sources', async () => { + const wrapper = mount(DatePicker, { + props: { + modelValue: ['2023', '12'], + columnsType: ['year', 'month'], + minDate: new Date(2023, 5, 1), + maxDate: new Date(2024, 5, 1), + }, + }); + + await wrapper.setProps({ modelValue: ['2024', '01'] }); + const selectedItems = wrapper.findAll('.van-picker-column__item--selected'); + expect(selectedItems[0].text()).toEqual('2024'); + expect(selectedItems[1].text()).toEqual('01'); + + await wrapper.find('.van-picker__confirm').trigger('click'); + expect( + wrapper.emitted<[PickerConfirmEventParams]>('confirm')![0][0].selectedValues + ).toEqual(['2024', '01']); +});