这是我的代码,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代码:
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';
}
}
})
我想要单击“选择”时,将显示测验答案。但是,当我单击“选择”时,什么也没发生。怎么了?有人可以帮助我吗?
答案 0 :(得分:5)
更改行:
this.selected[key] = 'selected';
收件人:
this.$set(this.selected, key, 'selected');
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/vue@2.5.16/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>