Vuelidate with Vue 3 + vue-class-component + TypeScript
Asked Answered
L

1

6

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.

Lacasse answered 7/4, 2021 at 13:29 Comment(0)
A
7

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/[email protected]

Amalamalbena answered 8/4, 2021 at 0:25 Comment(3)
I don't understand why this was marked as an answer, because when I try v-model="v$.login...'s "login" does not exist on type. – Nonfeasance
@ScumSprocket, it's hard to say retrospectively, but it worked for me back then. Personally I think it all doesn't matter anymore since vue-class-component is considered deprecated. The official vue-class-component docs state: "It is no longer recommend to use Class-based components in Vue 3. The recommended way to use Vue 3 in large applications is Single-File Components, Composition API, and <script setup>." – Lacasse
Yes, I have moved on from the class-component extensions. Long live, "script setup!" – Nonfeasance

© 2022 - 2024 — McMap. All rights reserved.