vue:从数组内的对象访问指定的数组



我想在一个页面中只显示一个questions数组,具体取决于用户选择的类别。

faqData = [
{
name: "first-category",
questions: [
{
id: 1,
question: "First question?",
answer: "First Answer"
},
{
id: 2,
question: "Second question?",
answer: "blablablabla"
}
]
},
{
name: "second-category",
questions: [
{
id: 1,
question: "First question?",
answer: "First Answer"
},
{
id: 2,
question: "Second question?",
answer: "blablablabla"
}
]
},
{
name: "third-category",
questions: [
{
id: 1,
question: "First question?",
answer: "First Answer"
}
]
}
];

vue文件

<div class="accordion" role="tablist" v-for="eachQuestion in questionList.questions" :key="eachQuestion.id">
<FAQCollapses v-bind:eachQuestion="eachQuestion" />
</div>
//script
data () {
return {
questionList: faqData
}
}

我的模板代码显示了一个空白的空间,在控制台中没有任何东西,所以我很困惑错误在哪里。问题是我不知道如何具体地从faqData数组中只获得一个类别,这取决于用户单击的类别。有人能告诉我实现我的目标的最佳实践是什么吗?我在StackOverflow中读过所有类似的问题,但它在我的情况下不起作用。非常感谢。

最好的方法(和最佳实践,我猜),它实现计算prop与名称,例如selectedFaqQuestion:

computed: {
selectedFaqQuestion () {
return selectedCategory ? this.faqData.find(category => category.name === this.selectedCategory).questions : []
}
}

并将其用于v-for:

<div v-for="eachQuestion in selectedFaqQuestion" :key="eachQuestion.id">
<FAQCollapses v-bind:eachQuestion="eachQuestion" />
</div>

当然,要做到这一点,您需要实现新的数据道具selectedCategory,您将在用户单击时存储所选类别:

data () {
return {
questionList: faqData,
selectedCategory: null
}
}

所以,正如你提到的,你需要处理用户点击,当要看到基于所选类别的任何问题。要处理它的点击,您需要使用v-on:click。要传递所选类别的新值,您需要更新它:selectedCategory = 'somecategoryname'

'somecategoryname'表示faqData prop 'name'中的内容,例如first-category:

<div> Please, peek FAQ category to show answers: 
<span v-on:click="selectedCategory = 'first-category'"> First category </span>
<span v-on:click="selectedCategory = 'second-category'"> Second category </span>
</div>

最新更新