fix: sueForm support dynamic rule, close #4799

pull/4825/head
tangjinzhou 2021-10-25 15:00:41 +08:00
parent 4fc7c1666a
commit 7d67e0e7f2
1 changed files with 35 additions and 35 deletions

View File

@ -1,5 +1,5 @@
import type { Ref } from 'vue';
import { computed, reactive, watch, nextTick, unref } from 'vue';
import { reactive, watch, nextTick, unref, shallowRef } from 'vue';
import cloneDeep from 'lodash-es/cloneDeep';
import intersection from 'lodash-es/intersection';
import isEqual from 'lodash-es/isEqual';
@ -120,30 +120,7 @@ function useForm(
const initialModel = cloneDeep(unref(modelRef));
const validateInfos = reactive<validateInfos>({});
const rulesKeys = computed(() => {
return rulesRef ? Object.keys(unref(rulesRef)) : [];
});
watch(
rulesKeys,
() => {
const newValidateInfos = {};
rulesKeys.value.forEach(key => {
newValidateInfos[key] = validateInfos[key] || {
autoLink: false,
required: isRequired(unref(rulesRef)[key]),
};
delete validateInfos[key];
});
for (const key in validateInfos) {
if (Object.prototype.hasOwnProperty.call(validateInfos, key)) {
delete validateInfos[key];
}
}
Object.assign(validateInfos, newValidateInfos);
},
{ immediate: true },
);
const rulesKeys = shallowRef([]);
const resetFields = (newValues: Props) => {
Object.assign(unref(modelRef), {
@ -350,6 +327,39 @@ function useForm(
const debounceOptions = options?.debounce;
let first = true;
watch(
rulesRef,
() => {
rulesKeys.value = rulesRef ? Object.keys(unref(rulesRef)) : [];
if (!first && options && options.validateOnRuleChange) {
validate();
}
first = false;
},
{ deep: true, immediate: true },
);
watch(
rulesKeys,
() => {
const newValidateInfos = {};
rulesKeys.value.forEach(key => {
newValidateInfos[key] = Object.assign({}, validateInfos[key], {
autoLink: false,
required: isRequired(unref(rulesRef)[key]),
});
delete validateInfos[key];
});
for (const key in validateInfos) {
if (Object.prototype.hasOwnProperty.call(validateInfos, key)) {
delete validateInfos[key];
}
}
Object.assign(validateInfos, newValidateInfos);
},
{ immediate: true },
);
watch(
modelRef,
debounceOptions && debounceOptions.wait
@ -358,16 +368,6 @@ function useForm(
{ immediate: options && !!options.immediate, deep: true },
);
watch(
rulesRef,
() => {
if (options && options.validateOnRuleChange) {
validate();
}
},
{ deep: true },
);
return {
modelRef,
rulesRef,