Utilizing vuelidate in Vue 3: Overcoming Decorators Challenge in Composition API (`<script setup>`)

Currently working on upgrading from vue 2 to vue 3 and encountering an error with the @Component decorator:

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

Showcasing my code below.

<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 you have a solution for this issue, kindly provide it. Thank you!

Answer №1

It appears there is an alternate documentation for integrating vuelidate with Vue 3.

To adapt the provided example to suit your specific needs and utilize <script setup>, it should resemble the following:

<script setup>
import { reactive } from 'vue'
import { useVuelidate } from '@vuelidate/core'
import { required, email } from '@vuelidate/validators'
// Other necessary imports

const state = reactive({
  userName: '',
  email: ''
})

const rules = {
  userName: { required },
  email: { required, email }
}

const v$ = useVuelidate(rules, state)
</script>

Answer №2

If you're considering migrating from Vue2 with property-decorator and class style syntax to Vue3, please take a look at this helpful discussion.

I encountered the same challenge when attempting to transition my large Vue2 project that heavily utilized "vue-property-decorator" to Vue3. Unfortunately, "vue-property-decorator" is no longer supported in Vue3, as noted in this GitHub issue: #294 Vue 3.0 support

In order to successfully migrate, I had to first move to Vue 2.7 (which supports Composition API), rewrite all components using Composition API, and then proceed with moving to Vue3.

However, it appears that there may be a workaround for using "vue-property-decorator" with Vue3 as discussed in the previous link provided. It's definitely worth exploring further.

Answer №3

If you're looking to make the switch from vue-class-component or vue-property-decorator to something different, consider giving vue-facing-decorator a try. This alternative is now being recommended in the deprecation notices of both packages.

We have personally had success using it to migrate our class components to Vue 3.

https://medium.com/@robert.helms1/vue-2-to-vue-3-with-class-components-cdd6530a2b2a

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up Vue.js API endpoints

I'm a newbie in VueJS, and I recently started using RxJS, Vue rx, and Vue Resource in a mixin to facilitate making HTTP calls and receiving observables anywhere... it's fantastic! Now, I decided to experiment with the following code: subscripti ...

Leverage a JavaScript plugin from the node modules directory within your Vue.js project

Is there a way to import Cal-HeatMap (https://www.npmjs.com/package/cal-heatmap) into my project after saving it with npm install? This is the method I attempted: <script> import calHeatmap from 'cal-heatmap' export default { na ...

How can we stop Vuetify from overwriting Bootstrap3's classes when using treeshaking?

I am currently in the process of transitioning an app from jQuery/Bootstrap3 to Vue/Vuetify. My approach is to tackle one small task at a time, such as converting the Navbar into its own Vue component and then gradually updating other widgets. Since the n ...

What is the best way to showcase this information within my columns?

I'm facing an issue with VueJS. I have a large dataset that I want to display in columns in a specific order. How can I properly insert the code for this? Thank you for any assistance. [ { "sort": 0, "title": "My title", "description": ...

Separate configurations in vue.config.js for running npm serve and npm build scripts

When it comes to customizing the webpack configuration, I am utilizing vue.config.js: const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: 'http://0.0.0.0:8080', outputDir: './dist/', chainWeb ...

Utilizing numerous Nuxt vuetify textfield components as properties

Trying to create a dynamic form component that can utilize different v-models for requesting data. Component: <v-form> <v-container> <v-row> <v-col cols="12" md="4"> <v ...

Creating a Commentary System in VueJS Similar to Medium

One feature that I admire in Medium is their commenting interface, which allows users to highlight specific portions of an article and leave comments. I am interested in integrating a similar commenting feature into a VueJS application. While researching ...

Passing arguments with $emit - Vue

Here is a simple method to handle alerts using $emit. But when passing arguments, it seems like the event is not being triggered at all. The goal is to update the value of alert with the result. Listening for the event on mount: this.$eventHub.$on(' ...

My experience with the Vue.js program has been disappointing as it is failing

Below is an example of my Vue.js code: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport&quo ...

The Vuejs component I created is failing to display on my Blade View

I can't seem to render my Vuejs component in my blade view. Any idea what I might be doing wrong? The specific component causing issues is named "star-rating". Blade View <div class="container"> <div class="row"> <div class="col- ...

Unable to access webpack-stats.json. Please verify that webpack has created the file and the path is accurate

After setting up django with Vue, I encountered a runtime error: Error reading webpack-stats.json. Have you ensured that webpack has generated the file and the path is accurate? https://i.stack.imgur.com/jfeET.jpg Next to manage.py, the following command ...

Setting up Jest configuration for integrating supertest with Vue framework

I have a unique application that utilizes both vue and express. I have separate tests for each, allowing me to run either a vue test or an express test independently. Below is the customized jest config file. This configuration works perfectly for Vue tes ...

Tips for personalizing the file names generated by Vue CLI?

Struggling to locate instructions for reducing assets and generating *.min.js files with vue cli. Currently running vue cli version 4.2.3. The file extension must be *.min.js for rollbar to work properly. Any suggestions on setting up vue cli to generate ...

Navigate to the Vuex Store to gain entry into the module

I have a module called ProfileData with the following structure: export const ProfileData = { state: { ajaxData: null; }, getters: {/*getters here*/}, mutations: {/*mutations here*/}, actions: {/*actions here*/} } This module ...

What is the best way to incorporate a vanilla javascript function into a vue.js application?

Consider a vanilla JavaScript function like this: if (window.devicePixelRatio >= 2) { document.querySelectorAll('img.retina').forEach(function (e) { let parts = e.src.split('.'); let ext = parts.pop(); i ...

Conceal the countdown clock and reveal the message box

I am attempting to create a functionality where the text box will replace the timer when it reaches 0, and then the timer will be hidden. I am seeking a straightforward solution using either the 'v-show' or 'destroy' property in vue.js ...

"I encountered an error while sorting lists in Vue 3 - the function this.lists.sort is not

Creating a Vue 3 front-end template: <template> <div class="container"> <router-link to="/user/create" class="btn btn-success mt-5 mb-5">Add New</router-link> <table class=" ...

A comprehensive guide on executing tasks prior to offering downloadable assets in Vue

In my Vue project, I am looking for a way to monitor file downloads. The idea is to generate a URL such as mysite.com/some/path/file-name.txt/tracking-source, trigger an action like sending the path to a tracking API, and then serve the file at mysite.com/ ...

What is the process for importing something from index.js within the same directory?

My folder structure is similar to the one below /components/organisms -- ModuleA.vue -- ModuleB.vue -- index.js The content of index.js: export { default as ModuleA } from "./ModuleA.vue" export { default as ModuleB } from "./ModuleB.vue&qu ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...