[Vuejs]-Toggling button color on click in Vue.js

2👍

in:

<button @click="handleClick($index, $parent.$index)"
      :class="{'green': turn}"
      >{{slot}}</button>

you are binding green class to every button just because turn is true .
You should also check if the point in this array corresponding to that button is marked as checked.

EDIT:

HTML:

<button @click="handleClick($index, $parent.$index)"
   v-bind:class="{ 'green': isGreen($index, $parent.$index), 'blue': isBlue($index, $parent.$index)}">
            {{slot}}
</button>

use 2 functions to check which class to bind.

in JS:

handleClick: function(index, parent){
      this.turn = !this.turn;
      this.turn ? this.board[parent][index] = greenDisk : this.board[parent][index]= blueDisk; 
    },
isGreen: function(index,parent){
 return (this.board[parent][index] == greenDisk);
},
isBlue: function(idx1,idx2){
 return !(this.turn == null) && (this.board[idx2][idx1] == blueDisk);
}

Why I check this.turn is not null in isBlue?
Because when You click button 2 variables change – turn and board.
Unfortunately vue is not very good when it comes to observing changes in arrays (push etc are ok). So it wont fire any reactivity magic with class bindings… unless we also use turn variable in one of those functions. These way vue knows that when variable turn changes (every click) it should also revalidate class bindings.

codepen:
http://codepen.io/lukpep/pen/KMgaNP

👤lukpep

Leave a comment