【问题标题】:Vuejs typescript class based components cannot update data from external api基于 Vuejs typescript 类的组件无法从外部 api 更新数据
【发布时间】:2018-08-30 18:01:56
【问题描述】:

我将 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() 装饰器将 Prop 切换为 data。这会导致以下错误:

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.

显然,我正在用砰的一声初始化它。我不知道出了什么问题。

【问题讨论】:

  • 你正试图改变一个prop。你应该只改变data
  • 否则你就违反了单向数据流的概念,vue绝对不允许你这样做,如错误所示
  • 如果我删除 @Prop() 装饰器,我会收到一个 vue 警告,upcomingexams 在实例上未定义,但在渲染期间被引用
  • 你正在向组件传递一个道具,你想将道具保存在数据属性中
  • 您不能修改不是由该组件单独控制的组件中的数据。当然,除非你使用像 vuex 或 Flux 这样的概念

标签: typescript vue.js


【解决方案1】:

在摸索了大约一个小时后,我发现由于某种原因,bang 初始化不能很好地与 Vue 配合使用。将upcomingexams 的声明切换为

upcomingexams: Exam[] = []; 让它工作。

【讨论】:

  • 为了提供更多上下文,在 vue 组件中初始化属性时,vue 会向属性添加 getter 和 setter,以便它可以跟踪和处理更改。当一个属性设置为 null 时,就像你原来的一样,它不能添加那些 setter/getter,从而使属性对动态数据无用
猜你喜欢
  • 1970-01-01
  • 2017-04-16
  • 1970-01-01
  • 2018-07-22
  • 2020-08-03
  • 1970-01-01
相关资源
最近更新 更多