【发布时间】:2020-08-16 13:38:10
【问题描述】:
我正在尝试使用 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 比较陌生,所以任何帮助将不胜感激。谢谢!
【问题讨论】:
-
我怀疑这与您在函数内部使用“this”引用主要对象属性有关。 'this' 是特定于上下文的,因此在您的方法中,它将是方法对象而不是您的主要方法
-
@GlynnHurrell 我最初让它们没有“this”,但这也没有用
-
如果不使用它,它们将是本地属性。您是否尝试过将“this”传递给函数构造函数,所以 qNext: function(obj) { obj.currentQuestion = obj.questionParts[obj.curr++] } 然后调用 qNext(this)
-
@GlynnHurrell 不,但我现在就试试!
标签: javascript vue.js methods iterator vue-component