Skip to content

Commit

Permalink
fix: prioritize the current value if another field of same name is mo…
Browse files Browse the repository at this point in the history
…unted closes #3429
  • Loading branch information
logaretm committed Aug 5, 2021
1 parent a85973c commit cf036ec
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/vee-validate/src/useField.ts
Expand Up @@ -486,8 +486,11 @@ export function useFieldValue<TValue>(
return ref(unref(initialValue)) as WritableRef<TValue>;
}

// set initial value
form.stageInitialValue(unref(path), unref(initialValue));
// to set the initial value, first check if there is a current value, if there is then use it.
// otherwise use the configured initial value if it exists.
// #3429
const currentValue = getFromPath(form.values, unref(path), unref(initialValue));
form.stageInitialValue(unref(path), currentValue === undefined ? unref(initialValue) : currentValue);
// otherwise use a computed setter that triggers the `setFieldValue`
const value = computed<TValue>({
get() {
Expand Down
28 changes: 28 additions & 0 deletions packages/vee-validate/tests/Form.spec.ts
Expand Up @@ -2205,4 +2205,32 @@ describe('<Form />', () => {

expect(value.value).toBe(undefined);
});

// #3429
test('Two fields of the same name should not override each other value when either is mounted', async () => {
const isHidden = ref(false);
const value = ref('');
mountWithHoc({
setup() {
return {
value,
isHidden,
};
},
template: `
<VForm>
<Field name="name" type="text" v-model="value" />
<Field v-if="isHidden" name="name" type="text" v-model="value" />
</VForm>
`,
});

await flushPromises();
const input = document.querySelector('input') as HTMLInputElement;
setValue(input, '1234');
await flushPromises();
isHidden.value = true;
await flushPromises();
expect(input.value).toBe(value.value);
});
});

0 comments on commit cf036ec

Please sign in to comment.