Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS set data in methods function

Tags:

vue.js

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???

like image 268
Toàn Avatar asked Mar 05 '23 20:03

Toàn


1 Answers

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>
like image 50
Psidom Avatar answered Mar 19 '23 06:03

Psidom