Skip to content

Commit

Permalink
fix: avoid unsetting field value if switched with another closes #3166
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Feb 9, 2021
1 parent 9ffc94b commit f5a79fe
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/vee-validate/src/useForm.ts
Expand Up @@ -295,6 +295,13 @@ export function useForm<TValues extends Record<string, any> = Record<string, any
// in this case, this is a single field not a group (checkbox or radio)
// so remove the field value key immediately
if (field.idx === -1) {
// avoid un-setting the value if the field was switched with another that shares the same name
// #3166
const isSharingName = fields.value.find(f => unref(f.name) === fieldName);
if (isSharingName) {
return;
}

unsetPath(formValues, fieldName);
unsetPath(initialValues.value, fieldName);
return;
Expand Down
58 changes: 58 additions & 0 deletions packages/vee-validate/tests/Form.spec.ts
Expand Up @@ -1565,4 +1565,62 @@ describe('<Form />', () => {
await flushPromises();
expect(input.checked).toBe(false);
});

// #3166
test('fields replacing others with the same name should have their value set correctly', async () => {
const data = [
{
id: 1,
title: 'this is a test no 1',
},
{
id: 2,
title: 'this is a test no 2',
},
{
id: 3,
title: 'this is a test no 3',
},
{
id: 4,
title: 'this is a test no 4',
},
];
let setModified!: (field: { id: number; title: string }) => void;
mountWithHoc({
setup() {
const fields = ref(data);
const modified = ref({ id: -1, title: '' });
setModified = (item: { id: number; title: string }) => {
modified.value = { ...item };
};

return {
fields,
setModified,
modified,
};
},
template: `
<VForm>
<ul>
<li v-for="field in fields" :key="field.id">
<Field v-if="modified.id === field.id" name="test" v-model="modified.title" type="text" as="input" />
</li>
</ul>
</VForm>
`,
});

await flushPromises();

const input = () => document.querySelector('input');
setModified(data[3]);
await flushPromises();
expect(input()?.value).not.toBe('');

setModified(data[2]);
await flushPromises();
expect(input()?.value).not.toBe('');
});
});

0 comments on commit f5a79fe

Please sign in to comment.