Having trouble locating variables in VueJS3 when using Axios and TypeScript?

I am facing an issue where I am unable to access the this.somethingHere variables inside methods using axios in combination with vuejs3 and TypeScript.

Template code (not required):

<template>
  <div>
    <form>
      <label for="email"> E-mail </label>
      <input
        type="email"
        placeholder=""
        name="email"
        id="email"
        v-model="email"
      />
      <br /><br />
      <label for="password"> Senha </label>
      <input
        type="password"
        placeholder=""
        v-model="password"
        name="password"
        id="password"
      />
      <br /><br />
      <button @click="doLogin" type="button">Enviar</button>
    </form>
  </div>
</template>

IMPORTANT: My vueJS code:

<script lang="ts">
import { axios } from "../services/config";

interface Login {
  email: string;
  password: string;
}

export default {
  data(): { email: string; password: string; data: string } {
    return {
      email: "",
      password: "",
      data: "",
    };
  },
  methods: {
    async doLogin(): Promise<void> {
      let userData: Login = {
        email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e2a36373f393170283f323b302a3b1e283f323b302a3b703d3133">[email protected]</a>",
        password: "myPassword",
      };
      try {
        const response: string = await axios.post("/login", userData);
        this.data = response;
      } catch (error) {
        this.data = "Error: " + error;
      }
    },
  },
};
</script>

Upon trying to build (save), I encountered the following error:

ERROR in src/views/Login.vue:52:14
TS2339: Property 'data' does not exist on type '{ doLogin(): Promise<void>; }'.
50 |         this.data = response;
51 |       } catch (error) {
> 52 |         this.data = "Error: " + error;
| ^^^^
53 |       }
54 |     },
55 |   },

If I disable TypeScript, everything works fine. However, sometimes it works but upon saving again, I encounter an error.

Answer №1

To achieve type inference, utilize the defineComponent method on the component definition object:

import { defineComponent } from 'vue'

export default defineComponent({
  methods: {
    handleClick() {
      console.log(this.data)
    }
  }
})

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

Navigating to different HTML pages by utilizing <a> elements in Angular 2

As a newcomer to Angular 2, I've decided to build my personal website using this framework. The main page of my website contains bio information, while the other page will feature blog content. Both pages will have a shared header and footer, but diff ...

Issue with <BrowserRouter>: TS2769: No suitable overload for this call available

I encountered this error and have been unable to find a solution online. As a beginner in typescript, I am struggling to resolve it. The project was originally in JavaScript and is now being migrated to TypeScript using ts-migrate. I am currently fixing er ...

Turn off hover effect for the v-checkbox component in Vuetify 2

Is there a way to prevent the darkened circle from appearing behind a v-checkbox in Vuetify 2 when hovering over it? My v-checkbox is currently enclosed within a v-tab and a v-tooltip, although I'm not sure if that has any impact. <v-tab v-for=&quo ...

Guide to creating a procedure that simultaneously triggers multiple methods

Here is a method that I have: private async void GenerateCalendar(IEnumerable<DateTime> dates) { using (var db = new CalendarDbContext()) { foreach (var date in dates) { var event = await service.CreateEvent(new EventModel ...

When running "npm run build" in Vue.js Vue-cli, the CSS is compiled to set the image opacity to 1%

Executing npm run serve results in everything working correctly. After running npm run build, no errors are reported. Upon viewing the website, I noticed that the images in the gallery section were not visible. Upon inspecting the element, I found that t ...

Replace the # symbol with #! in Vue.js router

My client is interested in using AJAX crawling, even though it is deprecated. They want to utilize it because of another search engine that still supports it, such as yandex.ru. More information can be found here. I need to convert this link to this form ...

How can I include multiple components within a single template in Nuxt Vue?

Overview I attempted to build a Vue Nuxt Single Page Application with sample components. Within one component, I included two others but ran into an issue where nothing was being displayed in the browser. I am seeking guidance on how to resolve this and ...

What could be causing the "Failed to compile" error to occur following the execution of npm

Exploring react with typescript, I created this simple and basic component. import React, { useEffect, useState } from "react"; import "./App.css"; type AuthUser = { name: string; email: string; }; function App() { const [user, setUser] = useState& ...

Struggling with eliminating spacing between v-text-field elements and labels in Vuetify

Struggling to reduce the vast gap between rows in my Vuetify project. I've attempted using CSS and Vuetify spacing options, but haven't had any luck. Desired layout: https://i.sstatic.net/vYH5e.png Current layout: https://i.sstatic.net/pEEbS.p ...

What is the best way to manage asynchronous functions when using Axios in Vue.js?

When I refactor code, I like to split it into three separate files for better organization. In Users.vue, I have a method called getUsers that looks like this: getUsers() { this.isLoading = true this.$store .dispatch('auth/getVal ...

Displaying grouped arrays efficiently in Angular

I have received data from an API in the form of an array with objects structured like so: [ {"desc":"a", "menu": 1},{"desc":"b", "menu": 2},{"desc":"c", "menu": 1}, ...

Getting stuck when attempting to retrieve a value with an async function in Node.js

Need help getting the value after making a Google API call within an asynchronous function in a Google Cloud Function. async function getGoogleApiToken() { let jwtClient = new google.auth.JWT( privatekey.client_email, ...

React is throwing an error due to an unhandled rejection: Request did not succeed, status code 404

import React, { useEffect, useState } from 'react'; import axios from 'axios'; const PokemonApi = () => { const [selectedPokemon, setSelectedPokemon] = useState(); useEffect(() => { ...

Create a tuple type that encompasses all possible paths within a recursive object configuration

Consider the following templates for 'business' types, representing compound and atomic states: interface CompoundState<TName extends string, TChildren extends { [key: string]: AnyCompoundState | AnyAtomicState }> { type: 'parent&ap ...

difficulty in accessing data from local Node.js server on devices connected to the network using a React frontend interface

My client application is running on localhost:3001 while my server application is on localhost:3000 The server is listening on 0.0.0.0:3000 Data loads normally on my Mac, but I encounter an issue when trying to retrieve data on mobile devices within the ...

The lite-server is not compatible for initiating the Angular2 Quickstart

Struggling to get the Angular2 Quick start app up and running on my Windows system. Unfortunately, I've hit a roadblock with the "lite-server". Despite installing dependencies (npm install), when attempting to run the app (npm start), an error pops u ...

Customize Vue components for easy drag and drop functionality

I am attempting to implement custom draggable components using the vuedraggable package, but I am facing issues in making it work. Additionally, I want the functionality to copy the component instead of moving it altogether. Below is the code snippet: < ...

How to fix the "Module parse failed" issue when importing MP3 files in NextJS 14 TypeScript?

Starting a new NextJS project, I used the command npx create-next-app@latest. Within this project, I created a simple TSX component that takes an imported MP3 file as a prop. 'use client'; import Image from "next/image"; import audioI ...

Populate an empty value in a key-value pair by using the subsequent value

Replace an empty value in a key-value pair with the first value of the next key. myitems = { 'items1': [{first:true, second:false}, {first:true, second:true}], 'items2': [], //should be filled with {first:true, second:false} 'it ...

"Encountered a runtime error while trying to execute the doubleClick() function using Pro

Encountering the following issue: "WebDriverError: Unable to convert: Error 404: Not found" while running a test with protractor: browser.actions().doubleClick(elem).perform(); or browser.actions().click(elem).click(elem).perform(); Uncertain of t ...