[英]Toggling button color on click in Vue.js
我正在使用Vue.js制作gomoku風格的游戲,但遇到了麻煩。 單擊其中一個按鈕時,它應該將按鈕的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;
}
在:
<button @click="handleClick($index, $parent.$index)"
:class="{'green': turn}"
>{{slot}}</button>
您將綠色類綁定到每個按鈕,只是因為turn
為true。 您還應該檢查數組中與該按鈕相對應的點是否標記為選中。
編輯:
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
在isBlue
不為null
? 因為當你點擊按鈕2個變量的變化- turn
和board
。 不幸的是,當觀察數組的變化時,vue並不是很好(按一下就可以了)。 因此,它不會激發任何具有類綁定的反應性魔術……除非我們在這些函數之一中也使用turn
變量。 通過這種方式vue知道,當變量turn
發生更改(每次單擊)時,它也應該重新驗證類綁定。
codepen: http ://codepen.io/lukpep/pen/KMgaNP
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.