【问题标题】:Vuelidate sameAs can't read component's dataVuelidate sameAs 无法读取组件的数据
【发布时间】:2021-05-16 09:51:48
【问题描述】:

我无法让 Vuelidate sameAs 验证器正常工作。似乎 sameAs 验证器无法读取 this.password.new 因为根据我的调试, this 在 sameAs 函数中未定义。可能我做错了什么,但我无法找出问题所在。所有其他验证都运行良好。

export default {
    name: 'login',
    setup() {
        return { 
            v$: useVuelidate()
        }
    },
    data : function() {
        return {
            name : "",
            email : "",
            password : {
                new : "",
                newRepeated : ""
            }
        }
    }, 
    validations: {
        name: {
            required,
            minLength: minLength(3)
        },
        email: {
            required,
            email
        },
        password: {
            new : {
                required,
                strongPassword(password) {
                    return (
                        /[a-z]/.test(password) && //checks for a-z
                        /[0-9]/.test(password) && //checks for 0-9
                        /\W|_/.test(password) && //checks for special char
                        password.length >= 10
                    );
                }
            },
            newRepeated : {
                sameAs : sameAs(function() {return this.password.new})
            }
        }
    },
    methods: {

【问题讨论】:

    标签: javascript ionic-framework vue-component vuejs3 vuelidate


    【解决方案1】:

    有人建议我应该使用箭头函数来保留对 this 的引用。另一种方法是使用 .bind。现在,我得到了对 this 的引用,但验证器总是返回 false。

    我现在已经像这样定义了验证器:

          newRepeated : {
                sameAs : sameAs(function() {return this.password.new}.bind(this))
            }
    

    我正在做一些调试。 sameAs 验证器的代码如下:

        function sameAs (equalTo) {
      return function (value) {
        return unref(value) === unref(equalTo);
      };
    }
    

    看起来有点奇怪,在内部的return语句中,有一个字符串和一个函数的比较。当然,它总是返回 false。这是一个错误还是我理解错误?

    【讨论】:

      猜你喜欢
      • 2020-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 2019-10-23
      • 2017-11-12
      相关资源
      最近更新 更多