使用 Vue 3 + vue-class-component + TypeScript 进行 Vuelidate

Igo*_*rov 6 typescript vue.js vuelidate vue-class-components

有谁知道上述堆栈的任何工作示例?我知道 Vuelidate 在 Vue 3 方面仍然是 alpha,但我的猜测是,如果它可以与 Composition API 一起使用,那么应该有一个解决方法可以使其与类一起使用。

我正在尝试以下简单示例:

<template>
  <input
    v-model="v$.login.$model"
    :class="{ wrongInput: v$.login.$errors.lenght }"
    placeholder="Login"
  />
</template>

Run Code Online (Sandbox Code Playgroud)
<script lang="ts">
import { Vue } from 'vue-class-component';
import useVuelidate from '@vuelidate/core';
import { required } from '@vuelidate/validators';

export default class LoginForm extends Vue {
  login = '';

  v$ = useVuelidate();

  validations() {
    return {
      login: {
        required,
      },
    };
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

错误是:

Uncaught (in promise) TypeError: _ctx.v$.login is undefined
Run Code Online (Sandbox Code Playgroud)

文档说我需要以某种方式传递规则和状态来 useVuelidate ( ),但我无法弄清楚它是如何以及是否是错误的原因。任何帮助表示赞赏。

ton*_*y19 7

在您的示例中,validations是一个组件方法,但 Vuelidate 希望它作为组件选项。

修复方法是validations移至@Options

import { Vue, Options } from 'vue-class-component';
import useVuelidate from '@vuelidate/core';
import { required } from '@vuelidate/validators'

@Options({
validations: {
    login: { required }
  }
})
export default class LoginForm extends Vue {
  login = '';

  v$ = useVuelidate();
}
Run Code Online (Sandbox Code Playgroud)

测试用@vuelidate/core@2.0.0-alpha.15