问题描述
在阅读了 Vee Validate 4 的关于将组合 api 与自定义输入结合使用的文档后,我是否正确理解钩子 useField a 必须仅在输入组件内部调用(在我的示例中是 VInput.vue)?有什么方法可以在父组件中使用钩子功能吗? VInput 用于另一个不需要验证的功能,因此它将是额外的功能,为 out 项目中的全局组件添加 useForm 例如我有 List.vue
<template>
<form class="shadow-lg p-3 mb-5 bg-white rounded" @submit.prevent="submitPostForm">
<VFormGroup label="Title" :error="titleError">
<VInput v-model="postTitle" type="text" name="title" />
</VFormGroup>
<VFormGroup label="Body" :error="bodyError">
<VInput v-model="postBody" type="text" name="body" />
</VFormGroup>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</template>
<script>
import { ref,onMounted } from 'vue';
import { Form,useForm,useField } from 'vee-validate';
import * as Yup from 'yup';
export default {
components: { Form },setup() {
const schema = Yup.object().shape({
title: Yup.string().required(),body: Yup.string().min(6).required(),});
//hooks
const { handleSubmit } = useForm({ validationSchema: schema });
// No need to define rules for fields because of schema
const { value: postTitle,errorMessage: titleError } = useField('title');
const { value: postBody,errorMessage: bodyError } = useField('body');
//methods
const submitPostForm = handleSubmit(() => {
addPost({ title: postTitle,body: postBody });
});
return { schema,postTitle,postBody,titleError,bodyError,submitPostForm };
},};
</script>
输入错误我只能在VFormGroup中显示的问题,如何管理这个表单?
解决方法
我不确定您是否正确理解了您的问题。
但在您的情况下,您只有 1 个问题,您在一个文件中对 errorMessage
和 value
进行了两次解构,但这是行不通的。
您可以像这样更改您的 useField
:
const { errorMessage: titleError,value: titleValue } = useField('title',Yup.string().required());
const { errorMessage: bodyError,value: bodyValue } = useField('body',Yup.string().required().min(8));
在您的 template
中,您希望在 titleError
中使用 bodyError
和 VFormGroup
。
在您的 VInput
中,您希望将 titleValue
和 bodyValue
用于 v-model
因为您在您的 title
中初始化了您的 body
和 setup()
我猜这些没有任何预定义值。如果是这种情况,您可能需要查看 useField()
的选项,您可以在其中将 thridParam 用作对象,例如initialValue
为 key
,然后将是您的 post.value.title
。但是对于您的用例,我不建议这样做。
从评论中回答代码问题:
<template>
<form class="shadow-lg p-3 mb-5 bg-white rounded" @submit="handleSubmit">
<VFormGroup label="Title" :error="titleError">
<VInput v-model="titleValue" type="text" name="title" />
</VFormGroup>
<VFormGroup label="Body" :error="bodyError">
<VInput v-model="bodyValue" type="text" name="body" />
</VFormGroup>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</template>
<script>
import { ref } from 'vue';
import { Form,useForm,useField } from 'vee-validate';
import * as Yup from 'yup';
export default {
components: { Form },setup() {
const title = ref('');
const body = ref('');
//hooks
const { handleSubmit } = useForm();
// No need to define rules for fields because of schema
const { errorMessage: titleError,Yup.string().required());
const { errorMessage: bodyError,Yup.string().required().min(8));
return { titleError,bodyError,titleValue,bodyValue,handleSubmit };
},};
</script>