首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Vue 2.6和Composition的Vuelidate

使用Vue 2.6和Composition的Vuelidate
EN

Stack Overflow用户
提问于 2021-06-11 21:50:06
回答 1查看 483关注 0票数 0

我将组合API与Vue 2(通过使用@vue/composition-api)和以下两个库(@vuelidate/core": "^2.0.0-alpha.18@vuelidate/validators": "^2.0.0-alpha.15)结合使用。

我正在尝试使用sameAs检查输入的电子邮件和重复的电子邮件是否匹配,如果不匹配则返回错误。尽管这并不像预期的那样顺利。

这是我的validation.js文件

代码语言:javascript
复制
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')
  },
}

这是我的validation-errors.js文件。(可能与这个问题无关)

代码语言:javascript
复制
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",
    },
  ],
}

这就是我试图在我的组件中使用它的方式。

代码语言:javascript
复制
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)
    }
 }
}

因此,当我在电子邮件和repeatEmail的输入域中输入相同的值时,它会给我一个无效值true。

EN

回答 1

Stack Overflow用户

发布于 2021-06-11 22:16:27

内置的验证器,比如sameAs don't have access to the state,,所以当像sameAs('email')一样使用时,它们是不能工作的。

这样,验证器应该在setup函数中定义,以便访问状态:

代码语言:javascript
复制
 const emailRef = computed(() => state.email);
 const validations = {
   ...
   repeatEmail: {
     ...
     sameAsEmail: sameAs(emailRef)
   },

否则,这需要使用自定义验证器来完成,而不是使用getCurrentInstance访问组件实例上的状态的内置验证器。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67938208

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档