Chr*_*lor 6 vue.js vee-validate
我有几个组件需要验证。问题是输入位于子组件中,而提交按钮位于父组件中,如下所示
父组件.js
<ValidationObserver v-slot="{ passes }">
<form @submit.prevent="passes(someSubmitFunction)">
<ChildComponent />
</form>
</ValidationObserver>
Run Code Online (Sandbox Code Playgroud)
子组件.js
<ValidationProvider rules="required" v-slot="{ errors }" name="vendorName">
<el-input />
</ValidationProvider>
Run Code Online (Sandbox Code Playgroud)
我在这里做错了什么?
对于像我这样的人,将来来这里寻求vee-validate v4以及Vue3 Composition API和Typescript的指导,我想建议这个答案。它的工作原理是将每个方法添加到一个数组中,然后在表单提交时它将循环遍历该数组以确保所有验证器异步通过。validateuseForm
表单聚合器.ts
import { InjectionKey, provide, ref } from "vue";
type ValidatorMethodType = () => Promise<{ valid: boolean }>;
export const AddValidatorKey: InjectionKey<
(validator: ValidatorMethodType) => void
> = Symbol("AddValidatorKey");
export function useValidationAggregator() {
const validators = ref<ValidatorMethodType[]>([]);
// used by components to add validators to the array
const register = (validator: ValidatorMethodType) => {
validators.value.push(validator);
};
// provide this aggregator to components
provide(AddValidatorKey, register);
// run all validators
const validateAll = async () => {
return Promise.all(validators.value.map((v) => v()));
};
return {
validateAll,
register,
};
}
Run Code Online (Sandbox Code Playgroud)
父组件.vue
<template>
<form @submit.prevent="onSubmit">
<ChildComponent />
<button type="submit" :disabled="inSubmit">Submit</button>
</form>
</template>
<script setup>
import useValidationAggregator from "./formAggregator.ts"
const { validateAll } = useValidationAggregator();
// note: you can use register() to also add validator from the parent component
const inSubmit = ref(false);
const onSubmit = async () => {
try {
inSubmit.value = true;
// run all form validators
const results = await validateAll();
// ensure all are valid
if (results.some((r) => !r.valid)) {
return;
}
// todo: post form or whatever you need after validation passes
} finally {
inSubmit.value = false;
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
子组件.vue
<template>
<!-- some validated fields -->
</template>
<script setup>
import { AddValidatorKey } from "./formAggregator.ts"
const { validate } = useForm({ ... setup validated fields ... });
// add this component's validator to the aggregator
const addValidator = inject(AddValidatorKey, () => {
throw new Error("No aggregator provided for inject");
});
addValidator(validate);
</script>
Run Code Online (Sandbox Code Playgroud)
幸运的是,有一种模式可以在父组件和子组件之间共享验证器范围!您可以将inject验证器从父级验证到子级,以便它们使用相同的实例。这意味着您可以使用以下方法验证来自父级的子级输入this.$validator.validate()
文档: http: //vee-validate.logaretm.com/v2/concepts/injections.html
| 归档时间: |
|
| 查看次数: |
5466 次 |
| 最近记录: |