typescript - 使用 Vue 3 + vue-class-component + TypeScript 的 Vuelidate

标签 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>

<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>

错误是:

Uncaught (in promise) TypeError: _ctx.v$.login is undefined

docs说我不知何故需要将规则和状态传递给 useVuelidate(),但我无法弄清楚它是如何以及是否是错误的原因。感谢您的帮助。

最佳答案

在您的示例中,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();
}

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

关于typescript - 使用 Vue 3 + vue-class-component + TypeScript 的 Vuelidate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66987113/

相关文章:

angular - zone.js 无法解析

typescript - Visual Studio Code : compile typescript module

javascript - Vue.js - 将同名的单选元素绑定(bind)到数组

vuelidate - 如何使用 vuelidate 验证电子邮件地址?

vue.js - Vue - 如何验证来自 Vuex 存储的数据

typescript - 在 asp core vs 2015 中禁用自动 Typescript 编译

javascript - 在大型 TypeScript 项目中共享类型的最佳方式?

javascript - 带返回值的多个嵌套 axios 调用

javascript - 如何使用 v-for 删除行

javascript - Vue-test-utils:在单个测试中多次使用 $nextTick