0

I am working on a gomoku style game using Vue.js, and I am stuck. When one of the buttons is clicked, it should change the background-color of that button to green, then if I click on another open spot, it should change the background-color to blue (thereby simulating each player's move). The problem with my program so far is that when I click on a button, it changes every empty spot to green instead of just the one I clicked. I am trying to do this in my index.html:

<ul>
  <li v-for="slots in board">
   <ul id="board">
    <li v-for="slot in slots">
      <button @click="handleClick($index, $parent.$index)"
      :class="{'green': turn}"
      >{{slot}}</button></li>
  </ul>
 </li>
</ul>

Then in my styles.css:

.green{
   background-color: #41B883;
}
.blue{
   background-color: #35495E;
}

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Would I do that checking inside the template or as a method in the vue instance?
That's perfect. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.