如何使用 Typescript 在自定义验证器中使用 Vuelidate Ref
How to use Vuelidate Ref in custom validator using Typescript
我正在尝试编写自定义 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
功能?
我通过在 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)
我正在尝试编写自定义 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
功能?
我通过在 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)