Skip to content

Commit

Permalink
fix: unregister fields once they are unmounted
Browse files Browse the repository at this point in the history
  • Loading branch information
logaretm committed Jul 23, 2020
1 parent 8393acc commit 0d601cb
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
1 change: 1 addition & 0 deletions packages/core/src/types.ts
Expand Up @@ -44,6 +44,7 @@ export type Flag =

export interface FormController {
register(field: any): void;
unregister(field: any): void;
values: ComputedRef<Record<string, any>>;
fields: ComputedRef<Record<string, any>>;
schema?: Record<string, GenericValidateFunction | string | Record<string, any>>;
Expand Down
18 changes: 17 additions & 1 deletion packages/core/src/useField.ts
@@ -1,4 +1,16 @@
import { watch, ref, Ref, isRef, reactive, computed, onMounted, toRefs, watchEffect, inject } from 'vue';
import {
watch,
ref,
Ref,
isRef,
reactive,
computed,
onMounted,
toRefs,
watchEffect,
inject,
onBeforeUnmount,
} from 'vue';
import { validate } from './validate';
import {
FormController,
Expand Down Expand Up @@ -105,6 +117,10 @@ export function useField(fieldName: MaybeReactive<string>, rules: RuleExpression
// associate the field with the given form
form.register(field);

onBeforeUnmount(() => {
form.unregister(field);
});

// extract cross-field dependencies in a computed prop
const dependencies = computed(() => {
const rulesVal = normalizedRules.value;
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/useForm.ts
Expand Up @@ -51,6 +51,14 @@ export function useForm(opts?: FormOptions) {

fields.value.push(field);
},
unregister(field: FieldComposite) {
const idx = fields.value.indexOf(field);
if (idx === -1) {
return;
}

fields.value.splice(idx, 1);
},
fields: fieldsById,
values,
schema: opts?.validationSchema,
Expand Down

0 comments on commit 0d601cb

Please sign in to comment.