版本
你好
我将 vee-validate 4 与 vuejs 3 和 yup 一起使用来创建“注册”表单。现在,由于我需要为每个输入字段设置样式(其中一些非常复杂),我正在尝试将验证逻辑添加到特定字段。
这是表格本身:
<template>
<div>
<Form @submit="onSubmit">
<PasswordField name="password" />
<PasswordField name="confirmpassword" confirm_field/>
<button class="submit-btn" type="submit">Submit</button>
</Form>
</div>
</template>
<script>
import { Form } from "vee-validate";
import PasswordField from "./components/PasswordField.vue";
export default {
name: "App",
components: {
PasswordField,
Form,
},
setup() {
function onSubmit(values) {
alert(JSON.stringify(values, null, 2));
}
return {
onSubmit,
};
},
};
</script>
这是自定义字段
<template>
<input :id="name"
:class="{'form-input': true, 'form-error': errors[0]}"
:name="name"
:value="inputValue"
type="password"
@change="onChange"
@input="onInput($event)"
/>
<span v-if="show_error">{{ errorMessage }}</span>
</template>
<script>
import {useField} from 'vee-validate';
import * as yup from 'yup';
export default {
name: 'PasswordField',
props: {
name: {
type: String,
required: true,
},
show_error: {
type: Boolean,
default: false
},
modelValue: {
type: String,
default: "",
},
confirm_field: {
type: Boolean,
default: false
}
},
setup (props) {
let rules = yup.string ().required ().min (5);
if (props.confirm_field) {
rules = yup.string ()
.required ().min (5)
.oneOf ([yup.ref ("password")])
}
const {
value: inputValue,
errors,
errorMessage,
handleBlur,
handleChange,
handleInput
} = useField (props.name, rules, {initialValue: props.inputValue});
return {
handleChange,
handleBlur,
errors,
errorMessage,
inputValue,
handleInput
};
},
watch: {
/* Syncs the value if it was updated from outside */
modelValue (val) {
this.inputValue = val;
}
},
methods: {
onInput (event) {
this.handleInput (event);
this.$emit ('update:modelValue', event.target.value);
},
onChange (event) {
this.handleChange (event);
}
},
};
</script>
confirmpassword-field 的验证失败:
<块引用>这必须是以下值之一:Ref(password)
因此似乎对密码输入的引用无法正常工作。
任何想法如何让这个工作?