VUE 3和TypeScrip-无法访问方法中的数据属性

我正在尝试使用我编写的方法访问我的数据,但似乎不起作用。我收到一个TS2339打印脚本错误,指出该属性在类型中不存在。

TS2339: Property 'players' does not exist on type '{ onAddPlayers(): void; getPlayerPlaceholder(index: number): string; }'.   
    47 |   methods: {
    48 |     onAddPlayers() {
  > 49 |       this.games = prepareGames(this.players as PadelPlayer[]);
       |                                      ^^^^^^^
    50 |     },
    51 |     getPlayerPlaceholder(index: number) {
    52 |       const playerNumber = Number(index) + 1;

以下是该组件的代码:

<script lang="ts">
import { PadelGame } from "@/models/padelGame.interface";
import { getPadelPlayers, prepareGames } from "../services/americanoService";
import { PadelPlayer } from "@/models/padelPlayer.interface";

const padelGames: PadelGame[] = [];

export default {
  data() {
    return {
      players: getPadelPlayers(),
      games: padelGames,
    };
  },
  methods: {
    onAddPlayers() {
      this.games = prepareGames(this.players as PadelPlayer[]);
    },
    getPlayerPlaceholder(index: number) {
      const playerNumber = Number(index) + 1;
      return "Spelare " + playerNumber;
    },
  },
};
</script>

解决方案

若要获得类型推断,应使用从VUE:

导入的defineComponent创建组件实例
<script lang="ts">
import { PadelGame } from "@/models/padelGame.interface";
import { getPadelPlayers, prepareGames } from "../services/americanoService";
import { PadelPlayer } from "@/models/padelPlayer.interface";
import {defineComponent} from 'vue'
const padelGames: PadelGame[] = [];

export default defineComponent({
  data() {
    return {
      players: getPadelPlayers(),
      games: padelGames,
    };
  },
  methods: {
    onAddPlayers() {
      this.games = prepareGames(this.players as PadelPlayer[]);
    },
    getPlayerPlaceholder(index: number) {
      const playerNumber = Number(index) + 1;
      return "Spelare " + playerNumber;
    },
  },
});
</script>

相关文章