我正在使用Vue.js开发一款五子棋风格的游戏,但我被卡住了。当其中一个按钮被点击时,它应该将该按钮的background-color更改为绿色,然后如果我单击另一个打开的点,它应该将background-color更改为蓝色(从而模拟每个玩家的移动)。到目前为止,我的程序的问题是,当我点击一个按钮时,它会将每个空白点都变成绿色,而不仅仅是我点击的那个。我正尝试在我的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;
}发布于 2016-06-18 16:26:09
在:
<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 is not null in isBlue?因为当您单击按钮2时,变量会发生变化- turn和board。不幸的是,当涉及到观察数组中的变化时,vue并不是很好(推送等都可以)。所以它不会使用类绑定来激发任何反应性魔法。除非我们在其中一个函数中也使用了turn变量。通过这种方式,vue知道当变量turn发生变化(每次单击)时,它也应该重新验证类绑定。
codepen:http://codepen.io/lukpep/pen/KMgaNP
https://stackoverflow.com/questions/37893138
复制相似问题