我正在尝试使用 vue.js 创建一个测验,但似乎无法弄清楚如何使“下一步”按钮迭代我的数据。希望屏幕显示包含问题和答案的对象(即问题一、问题二),然后在单击“下一步”时显示下一个对象。正如您将看到的,我在现有代码中进行了多次尝试,但没有成功。
测验组件模板:
<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”方法,但都不起作用。再次,我希望“下一个”能够迭代 [questionOne、questionTwo、questionThree]。我对 vue 比较陌生,所以任何帮助将不胜感激。谢谢!
最佳答案
当前实现的问题是您尝试在 questionOne
、questionTwo
和 的上下文中填充
不可访问,这意味着您的问题数组将填充未定义的值。questionParts
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
。
关于javascript - Vue.js - 单击按钮时迭代数据对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61553075/