This is my code, HTML:
<div id="myApp">
<div class="items">
<div class="item" v-for="quiz in quizzes" :key="quiz.id"}
<span>{{ quiz.question }}</span>
<span v-if="selected[quiz.key]">{{ quiz.answer }}</span>
<a href: "#" v-on:click="quizSelect(quiz.key, $event)">Select</a>
</div>
</div>
</div>
JS code:
new Vue({
el: '#myApp'
data: {
selected: {},
quizzes: [
{
key: 'k1',
question: 'This is question 1',
answer: 'This is answer 1'
},
{
key: 'k2',
question: 'This is question 2',
answer: 'This is answer 2'
}
]
},
methods: {
quizSelect: function(key, e) {
e.preventDefault();
this.selected[key] = 'selected';
}
}
})
I want when click to "Selecct", quiz anwser will show. But when i click "Select", nothing happend. What's wrong? Somebody can help me???
Change the line:
this.selected[key] = 'selected';
to:
this.$set(this.selected, key, 'selected');
See vue reactivity in depth.
new Vue({
el: '#myApp',
data: {
selected: {},
quizzes: [
{
key: 'k1',
question: 'This is question 1',
answer: 'This is answer 1'
},
{
key: 'k2',
question: 'This is question 2',
answer: 'This is answer 2'
}
]
},
methods: {
quizSelect: function(key, e) {
e.preventDefault();
this.$set(this.selected, key, 'selected');
// this.selected[key] = 'selected';
}
}
})
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="myApp">
<div class="items">
<div class="item" v-for="quiz in quizzes" :key="quiz.id">
<span>{{ quiz.question }}</span>
<span v-if="selected[quiz.key]">{{ quiz.answer }}</span>
<a href="#" v-on:click="quizSelect(quiz.key, $event)">Select</a>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With