pos*_*n23 0 vue.js vuelidate vue-composition-api
我将 Composition API 与 Vue 2(通过使用@vue/composition-api)结合使用,并结合以下两个库(@vuelidate/core": "^2.0.0-alpha.18、
@vuelidate/validators": "^2.0.0-alpha.15)。
我正在尝试检查sameAs输入的电子邮件和重复的电子邮件是否匹配,如果不匹配则返回错误。尽管这并没有想象中那么顺利。
这是我的validation.js文件
import { required, email, maxLength, sameAs } from "@vuelidate/validators";
export default {
email: {
required,
email,
maxLength: maxLength(100),
},
repeatEmail: {
required,
email,
maxLength: maxLength(100),
sameAsEmail: sameAs('email')
},
}
Run Code Online (Sandbox Code Playgroud)
这是我的validation-errors.js文件。(不过可能与这个问题无关)
export default {
email: [
{
key: "required",
message: "Email is required.",
id: "emailRequired",
},
{
key: "email",
message: "Wrong format on your email.",
id: "emailFormat",
},
{
key: "maxLength",
message: "Email can't be longer than 100 characters.",
id: "emailLength",
},
],
repeatEmail: [
{
key: "required",
message: "Email is required.",
id: "emailRequired",
},
{
key: "email",
message: "Wrong format on your email.",
id: "emailFormat",
},
{
key: "maxLength",
message: "Email can't be longer than 100 characters.",
id: "emailLength",
},
{
key: "sameAsEmail",
message: "Email isn't matching.",
id: "sameAsEmailFormat",
},
],
}
Run Code Online (Sandbox Code Playgroud)
这就是我尝试在我的组件中使用它的方式。
import validations from "@/validation";
import validationErrors from "@/validation-errors";
import { useVuelidate } from "@vuelidate/core";
import { reactive, toRefs } from '@vue/composition-api';
export default {
setup() {
const state = reactive({
email: "",
repeatEmail: "",
});
const $v = useVuelidate(validations, state);
return {
...toRefs(state)
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我在电子邮件和重复电子邮件的输入字段中正确输入相同的输入时,它会给我 true 作为无效值。
内置验证器sameAs 无法访问状态,因此它们在像sameAs('email').
这样验证器应该在setup函数中定义以便访问状态:
const emailRef = computed(() => state.email);
const validations = {
...
repeatEmail: {
...
sameAsEmail: sameAs(emailRef)
},
Run Code Online (Sandbox Code Playgroud)
否则,这需要使用自定义验证器来完成,而不是使用内置的验证器来访问组件实例上的状态getCurrentInstance。
| 归档时间: |
|
| 查看次数: |
2209 次 |
| 最近记录: |