Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/vant/src/field/Field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,13 @@ export default defineComponent({
},
);

watch(inputRef, (newVal) => {
if (newVal) {
updateValue(getModelValue(), props.formatTrigger);
nextTick(adjustTextareaSize);
}
});

onMounted(() => {
updateValue(getModelValue(), props.formatTrigger);
nextTick(adjustTextareaSize);
Comment on lines +689 to 698

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This new watch on inputRef and the existing onMounted hook have identical logic. Since a watcher's callback is fired before the onMounted hook during component setup, updateValue will be called twice if the input is present on initial mount. This is redundant and inefficient.

The new watch correctly handles both the initial mount case and the case where the input is dynamically added later. Therefore, the onMounted hook (lines 696-699) is no longer necessary and should be removed.

Expand Down
31 changes: 31 additions & 0 deletions packages/vant/src/field/test/index.spec.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Field } from '..';
import { mount, later } from '../../../test';
import { ref, nextTick } from 'vue';

test('should emit "update:modelValue" event when after inputting', () => {
const wrapper = mount(Field);
Expand Down Expand Up @@ -663,3 +664,33 @@ test('should limit maxlength correctly when pasting multiple emojis', async () =
expect(wrapper.emitted('update:modelValue')[0][0]).toEqual('1😀😀😀');
expect(input.element.value).toEqual('1😀😀😀');
});

test('should render correct value when input slot is removed dynamically', async () => {
const Wrapper = {
template: `
<Field v-model="value">
<template #input v-if="showSlot">
<div class="custom-input">Custom Input</div>
</template>
</Field>
`,
components: { Field },
setup() {
const value = ref('foo');
const showSlot = ref(true);
return { value, showSlot };
},
};

const wrapper = mount(Wrapper);

expect(wrapper.find('.custom-input').exists()).toBeTruthy();
expect(wrapper.find('input').exists()).toBeFalsy();

wrapper.vm.showSlot = false;
await nextTick();

const input = wrapper.find('input');
expect(input.exists()).toBeTruthy();
expect(input.element.value).toEqual('foo');
});
Loading