Search code examples
vue.jsvuejs3vue-composition-apivuelidate

Using vuelidate with Vue 3 : Decorators Issue with composition API (`<script setup>`)


I am doing vue upgrade from vue 2 to vue 3. There's an error in @Component decorator called

"Decorators are not valid here.ts(1206) (alias) Component(options: Vue.ComponentOptionsBase<Vue, any, any, any, any, any, any, any, string, {}, {}, string> & ThisType & ThisType): (target: VC) => VC (+1 overload) import Component"

This is my code.

<script setup>
  import { Component, Vue } from "vue-property-decorator";
  import apiService from "@/shared/services/apiService";
  import { validationMixin } from "vuelidate";
  import { required, email } from "vuelidate/lib/validators";
  import dirtyValidatorService from "@/shared/services/dirtyValidatorService";

  @Component({
    mixins: [validationMixin],
    validations: {
      userName: {
        required,
      },
      email: {
        required,
        email,
      },
    },
  })
  export const ForgotPassword = () => {
    userName: string = "";
    email: string = "";
    showSuccessMessage: boolean = false;
    showErrorMessage: boolean = false;
    dirtyValidatorRefNo: number = 0;
    dirtyValidationConfirmation: boolean = false;
    errorMessage: string = "";
    created = () => {
      this.dirtyValidatorRefNo = dirtyValidatorService.setInitialModel(
        this.dirtyValidatorRefNo,
        { userName: this.userName, email: this.email }
      );
    }
    SendForgotPasswordEmail = (isFormInvalid: boolean) =>{
      if (!isFormInvalid) {
        this.$store.dispatch("storeIsBusyValue", true);
        apiService
          .sendPostRequest("Account", "ResetPasswordEmail", {
            userName: this.userName,
            email: this.email,
          })
          .then((response) => {
            this.showErrorMessage = !response.data.isSuccess;
            this.showSuccessMessage = response.data.isSuccess;
            this.errorMessage = !response.data.isSuccess
              ? response.data.message
              : "";
            this.$store.dispatch("storeIsBusyValue", false);
          });
      }
    }
  }
</script>

If anyone knows to solve this, please mention it. Thanks and regards!


Solution

  • There seems to be a different documentation for using vuelidate with Vue 3.

    Adapting the example from the documentation to match your use case and using <script setup> should look like :

    <script setup>
    import { reactive } from 'vue'
    import { useVuelidate } from '@vuelidate/core'
    import { required, email } from '@vuelidate/validators'
    // And other imports
    
    const state = reactive({
      userName: '',
      email: ''
    })
    
    const rules = {
      userName: { required },
      email: { required, email }
    }
    
    const v$ = useVuelidate(rules, state)
    </script>