点击Vue.js

时间:2016-06-18 04:08:13

标签: javascript html css vue.js

我正在使用Vue.js进行gomoku风格的游戏,我被卡住了。单击其中一个按钮时,应将该按钮的background-color更改为绿色,然后如果单击另一个打开位置,则应将background-color更改为蓝色(从而模拟每个玩家&#39) ; s move)。到目前为止,我的程序存在的问题是,当我点击一个按钮时,它会将每个空白点更改为绿色,而不仅仅是我单击的那个。我试图在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>

然后在我的styles.css

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

1 个答案:

答案 0 :(得分:2)

在:

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

您将绿色类绑定到每个按钮只是因为turn为真。 您还应该检查此数组中与该按钮对应的点是否标记为已选中。

编辑:

HTML:

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

使用2个函数来检查要绑定的类。

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);
}

为什么我在this.turn中检查null不是isBlue? 因为当您单击按钮2时,变量会更改 - turnboard。 不幸的是,当观察数组中的变化时,vue不是很好(推送等等)。所以它不会用类绑定来激发任何反应性魔法......除非我们在其中一个函数中使用turn变量。这些方式vue知道当变量turn发生变化(每次点击)时,它也应该重新验证类绑定。

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