1 回答
TA贡献1900条经验 获得超5个赞
问题是你的答案是一个字符串,但你把它当作一个对象。尝试向其中添加active
属性是行不通的。
另一个问题是,如果修改answers
,它将影响所有问题,而不仅仅是一个问题。因为它们都共享同一个数组。
相反,我会修改您的examples
对象,以包含对象而不是字符串。该对象将包含用户选择的问题和答案。这样,每个问题都会有一个具体的答案,并且用户只能选择一个答案,因为它将覆盖旧值。
注: @click
是 的简写v-on:click
,:class
是 的简写v-bind:class
选项1:
new Vue({
el: '#app',
data: {
answers: {},
currentQuestion: {
examples: {
A: {
question: 'Lack zum Lackieren der Computergehäuse',
pickedAnswer: null
},
B: {
question: 'Elektrische Energie für die Montagewerkzeuge',
pickedAnswer: null
},
C: {
question: 'Silizium zur Herstellung der CPU',
pickedAnswer: null
},
D: {
question: 'Schrauben zum Befestigen von Bauteilen',
pickedAnswer: null
},
E: {
question: 'Zugekaufte Computergehäuse aus Stahlblech',
pickedAnswer: null
}
},
answers: {
'1': 'Rohstoff',
'2': 'Fremdbauteil',
'3': 'Hilfsstoff',
'4': 'Betriebsstoff'
},
rights: {
A: 3,
B: 4,
C: 1,
D: 3,
E: 2
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
<div
:key="index"
v-for="(example, index) in currentQuestion.examples"
class="row"
>
<div class="col-md-12">
<p class="p-3 mb-2 bg-dark text-white">{{ example.question }}</p>
</div>
<div
:key="index"
v-for="(answer, index, key) in currentQuestion.answers"
class="col-md-6"
>
<p>
<button
:class="{
'btn-primary': example.pickedAnswer == key,
'btn-secondary': example.pickedAnswer != key
}"
@click="example.pickedAnswer = key"
class="btn btn-lg btn-block"
>
{{ answer }}
</button>
</p>
</div>
</div>
</div>
examples
您可以向对象添加新属性,而不是将其转换为currentQuestion
对象。我pickedAnswers
在示例中调用了它,该对象将包含用户选择的答案。
选项2:
new Vue({
el: '#app',
data: {
answers: {},
currentQuestion: {
examples: {
A: 'Lack zum Lackieren der Computergehäuse',
B: 'Elektrische Energie für die Montagewerkzeuge',
C: 'Silizium zur Herstellung der CPU',
D: 'Schrauben zum Befestigen von Bauteilen',
E: 'Zugekaufte Computergehäuse aus Stahlblech'
},
pickedAnswers: {
A: null,
B: null,
C: null,
D: null,
E: null,
},
answers: {
'1': 'Rohstoff',
'2': 'Fremdbauteil',
'3': 'Hilfsstoff',
'4': 'Betriebsstoff'
},
rights: {
A: 3,
B: 4,
C: 1,
D: 3,
E: 2
}
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<div id="app">
<div
:key="index"
v-for="(example, questionKey, index) in currentQuestion.examples"
class="row"
>
<div class="col-md-12">
<p class="p-3 mb-2 bg-dark text-white">{{ example }}</p>
</div>
<div
:key="index"
v-for="(answer, key) in currentQuestion.answers"
class="col-md-6"
>
<p>
<button
:class="{
'btn-primary': currentQuestion.pickedAnswers[questionKey] == key,
'btn-secondary': currentQuestion.pickedAnswers[questionKey] != key
}"
@click="currentQuestion.pickedAnswers[questionKey] = key"
class="btn btn-lg btn-block"
>
{{ answer }}
</button>
</p>
</div>
</div>
</div>
- 1 回答
- 0 关注
- 96 浏览
添加回答
举报