【发布时间】:2019-04-29 08:02:04
【问题描述】:
我正在尝试根据父级 (App.vue) 中数组的状态来渲染组件。我完全不确定这是否是此用例的正确方法(Vue 新手且没有经验的程序员),所以如果您认为这不是考虑这个问题的正确方法,我很乐意接受建议。
我正在尝试构建一个包含一堆问题的疑难解答程序。每个问题都是一个组件,其数据如下所示:
data: function() {
return {
id: 2,
question: "Has it worked before?",
answer: undefined,
requires: [
{
id: 1,
answer: "Yes"
}
]
}
}
如果问题 1 的答案为“是”,则假定显示此问题。
我的问题是我不确定如何有条件地渲染我的组件。当前的方法是在响应组件时从组件发送事件,并在父组件中监听该事件。当事件触发时,父级更新一个数组,该数组包含所有已回答问题的“状态”。现在我需要从每个组件中检查这个数组,看看那里是否有已经回答的问题,如果满足正确的条件,则显示问题。
我的问题是:如何检查父级中的数据并根据它显示/隐藏我的组件?还有 - 这是个好主意还是我应该做一些不同的事情?
这里还有一些代码供参考:
App.vue
<template>
<div id="app">
<div class="c-troubleshooter">
<one @changeAnswer="updateActiveQuestions"/>
<two @changeAnswer="updateActiveQuestions"/>
</div>
</div>
</template>
<script>
import one from './components/one.vue'
import two from './components/two.vue'
export default {
name: 'app',
components: {
one,
two
},
data: function() {
return {
activeQuestions: []
}
},
methods: {
updateActiveQuestions(event) {
let index = this.activeQuestions.findIndex( ({ id }) => id === event.id );
if ( index === -1 ) {
this.activeQuestions.push(event);
} else {
this.activeQuestions[index] = event;
}
}
}
}
</script>
两个.vue
<template>
<div v-if="show">
<h3>{{ question }}</h3>
<div class="c-troubleshooter__section">
<div class="c-troubleshooter__input">
<input type="radio" id="question-2-a" name="question-2" value="ja" v-model="answer">
<label for="question-2-a">Ja</label>
</div>
<div class="c-troubleshooter__input">
<input type="radio" id="question-2-b" name="question-2" value="nej" v-model="answer">
<label for="question-2-b">Nej</label>
</div>
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
id: 2,
question: "Bla bla bla?",
answer: undefined,
requires: [
{
id: 1,
answer: "Ja"
}
]
}
},
computed: {
show: function() {
// Check in parent to see if requirements are there, if so return true
return true;
}
},
watch: {
answer: function() {
this.$emit('changeAnswer', {
id: this.id,
question: this.question,
answer: this.answer
})
}
}
}
</script>
【问题讨论】:
-
尝试将所有问题数据放入父级,并将其作为道具传递给子级。子组件可能可以制成一个通用问题组件,您可以将其用于所有问题。
requires可以是一个函数。如果以后有时间我会写一个答案。 -
是的,我意识到每个问题都有一个组件很奇怪,但我不确定我能做到多么模块化,因为每个问题的模板可能有点不同。例如,其中一些包含图像或自定义元素,而另一些则没有。也就是说,这些组件中的大多数基本上是相似的。
标签: javascript vue.js vuejs2 vue-component