【发布时间】: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