on单击"移动到下一个索引v-for"并进行渲染



我在vue中构建了一个测试组件,我的问题数组上有一个v-for循环。当点击一个答案时,我想把v-for索引移到下一个问题上。

目前它显示了我所有的问题,所以我需要隐藏所有其他问题,直到选择正确的答案,然后继续移动阵列。

我不确定这是否可能?

<v-card v-for="(question, index) in quizQuestions" :key="index" class="elevation-0" height="62vh" style="overflow: scroll">
<v-card-title class="text-h5 primary--text">Question {{ index + 1 }}</v-card-title>
<v-card-subtitle>{{ question.value.questionTitle }}</v-card-subtitle>
<v-card-text>
<v-btn v-for="(answer, index) in JSON.parse(question.value.answers)" :key="index" class="elevation-0 mr-4 rounded-lg" @click="checkAnswer(answer.correct, index)" x-large>
{{ answer.text }}
</v-btn>
</v-card-text>
<v-row class="d-flex flex-column" no-gutters>
<v-divider></v-divider>
<div>Question {{ index + 1}} of {{ quizQuestions.length }}</div>
<v-progress-linear height="3vh" class="rounded-xl" :value="quizQuestions.length"></v-progress-linear>
</v-row>
</v-card>

因此,您需要将v-card封装在template标记中,并在v-card上添加v-if条件,以仅显示等于currentIndex的问题索引。

<template v-for="(question, index) in quizQuestions">
<v-card v-if="index === currentIndex" :key="index" class="elevation-0" height="62vh" style="overflow: scroll">
<v-card-title class="text-h5 primary--text">Question {{ index + 1 }}</v-card-title>
<v-card-subtitle>{{ question.value.questionTitle }}</v-card-subtitle>
<v-card-text>
<v-btn
v-for="(answer, index) in JSON.parse(question.value.answers)"
:key="index"
class="elevation-0 mr-4 rounded-lg"
@click="checkAnswer(answer.correct, index)"
x-large
>
{{ answer.text }}
</v-btn>
</v-card-text>
<v-row class="d-flex flex-column" no-gutters>
<v-divider></v-divider>
<div>Question {{ index + 1 }} of {{ quizQuestions.length }}</div>
<v-progress-linear height="3vh" class="rounded-xl" :value="quizQuestions.length"></v-progress-linear>
</v-row>
</v-card>
</template>

js中,通过增加currentIndexcurrentIndex创建一个状态和一个函数以转到下一个问题。

data: {
return {
currentIndex: 0,
}
},
methods: {
nextQuestion() {
++this.currentIndex
}
}

您应该添加computed属性来显示活动问题,而不是您的v-for来显示所有问题,它应该看起来像这个

data: () => ({
activeQuestionIndex: 1,
quizQuestions: ["#f00", "#ccff00", "#eee", "#0f0"],
}),
computed:{
activeQuestion: function () {
return this.quizQuestions[this.activeQuestionIndex]
}
}

所以你删除了v-for,在你使用question.someproperty的任何地方,现在你都将使用activeQuestion.someporperty

你应该在你的checkAnswer函数中处理activeQuestionIndex增量

最新更新