Search code examples
typescriptvue.jsvuelidatevue-class-components

Vuelidate with Vue 3 + vue-class-component + TypeScript


Does anyone know any working example with the mentioned stack? I know Vuelidate is still alpha when it comes to Vue 3, but my guess is if it works with Composition API, then there should be a workaround to make it work with classes.

I'm trying the following simple example:

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

And the error is:

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

The docs says I somehow need to pass rules and state to useVuelidate(), but I can't figure how and whether it is the reason for the error. Any help is appreciated.


Solution

  • In your example, validations is a component method, but Vuelidate expects it as a component option.

    The fix is to move validations into @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();
    }
    

    Tested with @vuelidate/core@2.0.0-alpha.15