我正在尝试使用vue.js创建测验,但似乎无法弄清楚如何使“下一步”按钮遍历我的数据。希望屏幕显示包含答案的问题的对象(即questionOne,questionTwo),然后在单击“下一步”时显示下一个对象。如您所见,我已经在现有代码中进行了几次尝试,但是没有任何效果。
测验组件模板:
<template>
<div class="quiz-container">
<div
class="question-container">
<h1> {{ currentQuestion.q }} </h1>
</div>
<div class="answer-container">
<v-btn
v-for="answer in currentQuestion.ans"
:key="answer"
outlined
block
x-large
class="answer-btn"
>
{{ answer }}
</v-btn>
</div>
<div
class="navigation flex-row"
>
<v-btn text x-large @click="questionNav.curr--">Back</v-btn>
<v-spacer />
<v-btn text x-large @click="qNext()">Next</v-btn>
</div>
</div>
</template>
测验脚本:
<script>
import { mapGetters } from 'vuex';
export default {
name: 'quiz',
computed: {
...mapGetters('user', {
loggedIn: 'loggedIn'
})
},
data: () => ({
curr: 0,
currentQuestion: {
q: 'kasjdn' ,
ans: ['1', '2', '3']
},
questionOne: {
q: 'How many minutes do you want to spend?' ,
ans: ['Short (15-20)', 'Medium (20-40)', 'Long (40-60)']
},
questionTwo: {
q: 'What muscle group do you want to focus on?' ,
ans: ['Upper Body', 'Lower Body', 'Core', 'Full Body']
},
questionThree: {
q: 'What level intensity do you want?' ,
ans: ['Leisure Walking', 'Speed Walking', 'Jogging', 'Sprinting']
},
questionParts: [this.questionOne, this.questionTwo, this.questionThree]
}),
methods: {
questionNav: function () {
questionParts = [this.questionOne, this.questionTwo, this.questionThree]
currentQuestion = questionParts[curr]
},
qNext: function () {
this.currentQuestion = this.questionParts[this.curr++]
}
}
}
</script>
如您所见,我尝试了“ qNext”方法和“ questionNav”方法,但均无济于事。同样,我希望“ Next”通过[questionOne,questionTwo,questionThree]进行迭代。我对Vue较陌生,因此任何帮助将不胜感激。谢谢!
答案 0 :(得分:1)
当前实现的问题在于,您试图在无法访问questionParts
,questionOne
和questionTwo
的情况下填充questionThree
,这意味着您的问题数组将充满未定义的值。
总的来说,只要确保questionParts
确实包含问题对象,您所做的工作就应该起作用。如果要将这种逻辑保留在data
方法中,请按以下步骤操作:
data: () => {
const questionOne = {
q: 'How many minutes do you want to spend?' ,
ans: ['Short (15-20)', 'Medium (20-40)', 'Long (40-60)']
};
const questionTwo = {
q: 'What muscle group do you want to focus on?' ,
ans: ['Upper Body', 'Lower Body', 'Core', 'Full Body']
};
const questionThree = {
q: 'What level intensity do you want?' ,
ans: ['Leisure Walking', 'Speed Walking', 'Jogging', 'Sprinting']
};
const questionParts = [questionOne, questionTwo, questionThree]
return {
curr: 0,
currentQuestion: {
q: 'kasjdn' ,
ans: ['1', '2', '3']
},
questionOne,
questionTwo,
questionThree,
questionParts,
}
},
通过在实际返回data()
的值之前声明一些变量,您可以正确地填充questionParts
数组。这足以使您的测验生效。
您可能还需要考虑其他一些改进,例如:
questionOne
,questionTwo
和questionThree
对象,而是可以直接实例化一系列问题。给定您提供的代码示例,将每个问题作为一个单独的对象似乎并不是特别有用。currentQuestion
可以是返回索引curr
的问题的计算属性。这样,您就只能在点击处理程序中递增或递减curr
,并且无需您显式分配currentQuestion
即可使用计算属性来返回正确的问题。答案 1 :(得分:0)
qNext: function () {
this.currentQuestion.q = this.questionParts[this.curr++].q
this.currentQuestion.ans = this.questionParts[this.curr++].ans
}