Skip to content

Commit a7b91f6

Browse files
committed
fix: avoid validating dependencies via watcheffect closes #3156
1 parent 52fdb8a commit a7b91f6

1 file changed

Lines changed: 21 additions & 12 deletions

File tree

packages/vee-validate/src/useField.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import {
66
reactive,
77
computed,
88
onMounted,
9-
watchEffect,
109
onBeforeUnmount,
1110
unref,
1211
WatchStopHandle,
@@ -215,28 +214,38 @@ export function useField<TValue = any>(
215214
}
216215

217216
return Object.keys(rulesVal).reduce((acc: string[], rule: string) => {
218-
const deps = extractLocators((normalizedRules as Ref<Record<string, any>>).value[rule]).map(
219-
(dep: any) => dep.__locatorRef
220-
);
217+
const deps = extractLocators(rulesVal[rule]).map((dep: any) => dep.__locatorRef);
218+
221219
acc.push(...deps);
222220

223221
return acc;
224222
}, []);
225223
});
226224

225+
const dependenciesValues = computed(() => {
226+
return dependencies.value.reduce((acc, depName) => {
227+
if (depName in form.values) {
228+
acc[depName] = form.values[depName];
229+
}
230+
231+
return acc;
232+
}, {} as Record<string, unknown>);
233+
});
234+
227235
// Adds a watcher that runs the validation whenever field dependencies change
228-
watchEffect(() => {
229-
// Skip if no dependencies
230-
if (!dependencies.value.length) {
236+
watch(dependenciesValues, (deps, oldDeps) => {
237+
// Skip if no dependencies or if the field wasn't manipulated
238+
if (!Object.keys(deps).length || !meta.dirty) {
231239
return;
232240
}
233241

234-
// For each dependent field, validate it if it was validated before
235-
dependencies.value.forEach(dep => {
236-
if (dep in form.values && meta.dirty) {
237-
return validate();
238-
}
242+
const shouldValidate = Object.keys(deps).some(depName => {
243+
return deps[depName] !== oldDeps[depName];
239244
});
245+
246+
if (shouldValidate) {
247+
validate();
248+
}
240249
});
241250

242251
return field;

0 commit comments

Comments
 (0)