Skip to content

Commit 9046308

Browse files
committedMay 9, 2023
fix: remove path state with keep-values closes #4247
1 parent 9371f10 commit 9046308

File tree

3 files changed

+52
-1
lines changed

3 files changed

+52
-1
lines changed
 

‎.changeset/kind-bikes-turn.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'vee-validate': patch
3+
---
4+
5+
fixed validations running for unmounted fields

‎packages/vee-validate/src/useField.ts

+3-1
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,13 @@ function _useField<TValue = unknown>(
407407
onBeforeUnmount(() => {
408408
PENDING_UNMOUNT = true;
409409
const shouldKeepValue = unref(field.keepValueOnUnmount) ?? unref(form.keepValuesOnUnmount);
410+
const path = unravel(name);
410411
if (shouldKeepValue || !form) {
412+
form?.removePathState(path);
413+
411414
return;
412415
}
413416

414-
const path = unravel(name);
415417
const pathState = form.getPathState(path);
416418
const matchesId =
417419
Array.isArray(pathState?.id) && pathState?.multiple

‎packages/vee-validate/tests/Form.spec.ts

+44
Original file line numberDiff line numberDiff line change
@@ -3043,3 +3043,47 @@ test('unmounted radio fields gets unregistered and their values are removed if c
30433043
expect(errors.textContent).toBe('{}');
30443044
expect(JSON.parse(values.textContent)).toEqual({});
30453045
});
3046+
3047+
// #4247
3048+
test('unmounted fields should not be validated when keep-values is on', async () => {
3049+
let showFields!: Ref<boolean>;
3050+
const spy = vi.fn();
3051+
const wrapper = mountWithHoc({
3052+
setup() {
3053+
showFields = ref(true);
3054+
3055+
return {
3056+
showFields,
3057+
onSubmit(values: any) {
3058+
spy(values);
3059+
},
3060+
};
3061+
},
3062+
template: `
3063+
<VForm @submit="onSubmit" v-slot="{ errors }" keep-values>
3064+
<template v-if="showFields">
3065+
<Field name="test" rules="required" />
3066+
</template>
3067+
3068+
<button>Submit</button>
3069+
</VForm>
3070+
`,
3071+
});
3072+
3073+
await flushPromises();
3074+
const button = wrapper.$el.querySelector('button');
3075+
const inputs = wrapper.$el.querySelectorAll('input');
3076+
3077+
wrapper.$el.querySelector('button').click();
3078+
await flushPromises();
3079+
setValue(inputs[0], '');
3080+
3081+
showFields.value = false;
3082+
await flushPromises();
3083+
button.click();
3084+
await flushPromises();
3085+
const expected = {
3086+
test: '',
3087+
};
3088+
expect(spy).toHaveBeenLastCalledWith(expected);
3089+
});

0 commit comments

Comments
 (0)
Please sign in to comment.