1 回答

TA貢獻(xiàn)1900條經(jīng)驗 獲得超5個贊
問題是你的答案是一個字符串,但你把它當(dāng)作一個對象。嘗試向其中添加active
屬性是行不通的。
另一個問題是,如果修改answers
,它將影響所有問題,而不僅僅是一個問題。因為它們都共享同一個數(shù)組。
相反,我會修改您的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
您可以向?qū)ο筇砑有聦傩?,而不是將其轉(zhuǎn)換為currentQuestion
對象。我pickedAnswers
在示例中調(diào)用了它,該對象將包含用戶選擇的答案。
選項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 關(guān)注
- 138 瀏覽
添加回答
舉報