基于VueJS Typescript类的组件无法从外部api更新数据

时间:2018-08-30 18:01:57

标签: typescript vue.js

我正在将VueJS与Typescript和基于类的组件一起使用。我有以下代码可以给我

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "upcomingexams"

UpcomingExams.vue

<template>
    <div class="card">
        <ul class="examlist">
            <li v-for="exam in upcomingexams" :key="exam.examId">
                {{ exam.examId }} on {{ exam.start }}
            </li>
        </ul>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

export interface Exam {
  examId: string;
  questions: string[];
  correctAnswers: string[];
  start: Date;
  end: Date;
  course: string;
  schools: string[];
}

@Component
export default class UpcomingExams extends Vue {
@Prop() upcomingexams!: Exam[];

mounted() {
    console.log("UpcomingExams component mounted");
    this.getExamsAfterToday();
}

getExamsAfterToday() {
    var date = new Date();
    fetch("http://localhost:3000/api/queries/Q1?todayDatetime=" + date.toJSON())
    .then(response => response.json() as Promise<Exam[]>)
    .then(data => (this.upcomingexams = data));
}
}
</script>

我尝试通过移除Prop装饰器将data切换为@Prop()。这将导致以下错误:

Property or method "upcomingExams" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

很明显,我正在用爆炸声初始化它。我不知道怎么了。

1 个答案:

答案 0 :(得分:0)

大约一个小时后,我发现由于某种原因,bang初始化在Vue中不能很好地发挥作用。将upcomingexams的声明切换为

upcomingexams: Exam[] = [];使它起作用。