【问题标题】:How to use Vuelidate Ref in custom validator using Typescript如何使用 Typescript 在自定义验证器中使用 Vuelidate Ref
【发布时间】:2021-03-31 10:20:26
【问题描述】:

我正在尝试编写自定义 Vuelidate 规则以确保指定字段是另一个字段值之后的日期值。

这是我目前所写的:

export const isDateAfter: (field: string | ((vm: any, parentVm?: Vue) => any)) => ValidationRule = (field) => {
  return helpers.withParams(
    {type: "isDateAfter", message: "{{fieldName}} must be after {{min}}", min: field},
    (value: Date, vm: any) => {
      const fieldValue = helpers.ref(field, vm, ??? );
      return isAfter(fieldValue, value);
    }
  )
}

我的问题是将什么传递给helpers.ref 的第三个参数。所有 JavaScript 示例都将参数显示为 (field, this, vm),但我无法传递 this,因为我收到以下警告:

TS7041: The containing arrow function captures the global value of 'this'.

如何正确使用ref函数?

【问题讨论】:

    标签: typescript vue.js vuelidate


    【解决方案1】:

    我通过在 Vuelidate 之外创建自己的 ref 函数解决了这个问题:

    
    const ref: (reference: string | ((vm: any) => any), vm: any) => any = (reference, vm) => {
      return typeof reference === "function" ? reference(vm) : vm[reference];
    };
    

    这在自定义验证规则中使用:

    (value: Date, vm: any) => {
      const fieldValue = ref(field, vm);
      return isAfter(value, fieldValue);
    }
    
    

    并在表单验证器对象中使用:

    isDateAfter: isDateAfter((vm) => vm.startDate)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-17
      • 2022-07-13
      • 1970-01-01
      • 2021-08-03
      相关资源
      最近更新 更多