【问题标题】:VueJS3 with Axios and TypeScript - Cannot find variables带有 Axios 和 TypeScript 的 VueJS3 - 找不到变量
【发布时间】:2021-09-16 15:49:05
【问题描述】:

我无法使用 axios + vuejs3 + ts 访问方法内的 this.somethingHere 变量。

模板代码(非必须):

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

重要提示我的 vueJS 代码:

<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: "thiago.valente@valente.com",
        password: "myPassword",
      };
      try {
        const response: string = await axios.post("/login", userData);
        this.data = response;
      } catch (error) {
        this.data = "Error: " + error;
      }
    },
  },
};
</script>

当我尝试构建(保存)时,我收到当前错误:

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

如果我停用可以正常工作的打字稿。有时它可以工作,但如果我再次尝试保存,我会遇到错误。

【问题讨论】:

    标签: typescript vue.js async-await axios vuejs3


    【解决方案1】:

    在组件定义对象上使用defineComponent 来获取类型推断:

    import { defineComponent } from 'vue'
    
    export default defineComponent({
      methods: {
        doLogin() {
          console.log(this.data)
        }
      }
    })
    

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 2018-08-02
      • 2021-11-24
      • 2021-04-15
      • 2021-08-04
      • 2018-05-25
      • 2020-09-28
      • 2020-06-19
      • 2018-05-28
      相关资源
      最近更新 更多