【发布时间】:2020-11-12 18:53:49
【问题描述】:
背景
我有一个 Vue 组件 question-panel,它接受一个 prop questions,它是一个对象数组,长度可变。
在<template>...</template>中,有一些HTML元素用于显示计算出的question对象的信息,如question.name、question.score等。
还有两个按钮,点击时分别调用previousQuestion() 和nextQuestion()。
问题
根据 Vue.js devtools,prop questions 确实绑定并响应来自父级的更改。
但是,即使在 prop questions 更改之后,计算的 question 也不会重新计算。
另一方面,当questionIndex 更改时,它会重新计算。
我应该如何解决此问题?这个实现是不是违背了Vue的原则?
QuestionPanel.vue 的片段
<script>
export default {
props: {
questions: Array,
},
data() {
return {
questionIndex: 0,
};
},
computed: {
question: function () {
return this.questions[this.questionIndex];
},
},
methods: {
previousQuestion() {
if (this.questionIndex > 0) {
this.questionIndex--;
this.$emit("questionChanged", this.question);
}
},
nextQuestion() {
if (this.questionIndex < this.questions.length - 1) {
this.questionIndex++;
this.$emit("questionChanged", this.question);
}
},
},
};
</script>
Parent.Vue 的片段
<paper-panel
@questionsArrived="Object.assign(questions, $event)"
></paper-panel>
<question-panel
:questions="questions"
></question-panel>
Vue.js 开发工具屏幕
【问题讨论】:
-
您尝试使用
@watch,it 可能有帮助吗? -
如何在父节点上设置数组问题的新值?
-
如何更改父母提出的道具问题?某些更改可能不是被动的
-
@yuri @Oliver
:questions="questionsInParent",questionsInParent设置如下:<another-component @questionsArrived="Object.assign(questionsInParent, $event)>...</another-component>
标签: vuejs2 vue-component vue-reactivity vue-props