我有一个数组(历史记录),每按一次按钮就会被推送两个项目。这两个项目在打印时需要有不同的CSS样式。
HTML
<ul class="info">
<li :class="{ 'style-one' : toggle, 'style-two' : toggle }" v-for="item in history">{{item}}</li>
</ul>
JS(Vue)
methods: {
attack: function() {
this.history.unshift(this.playerDamaged);
this.history.unshift(this.monsterDamaged);
}
这个问题是在循环期间无法改变toggle
的真实性。有没有更好的方法来解决这个问题?
答案 0 :(得分:7)
您可以使用此代码:
<ul class="info">
<li v-for="item in history" :key="item"
:class="{ 'style-one' : item.isPlayer, 'style-two' : !item.isPlayer }"
>
{{ item.text }}
</li>
</ul>
methods: {
attack: function() {
this.history.unshift({ text: this.playerDamaged, isPlayer: true });
this.history.unshift({ text: this.monsterDamaged, isPlayer: false });
}
您可以使用没有对象的其他解决方案:
<ul class="info">
<li v-for="(item, index) in history" :key="item"
:class="'style-' + ((index % numberOfPlayers) + 1)"
>
{{ item }}
</li>
</ul>
//This part don't have to deal with Array of Objects :
methods: {
attack: function() {
this.history.unshift( this.playerDamaged );
this.history.unshift( this.monsterDamaged );
},
computed: {
numberOfPlayers: function() {
return 2;
}
}
如果你想添加一个玩家(例如:怪物2),你必须将计算出的numberOfPlayers更新为3(或更好:如果你有更新:listOfPlayers.length)并创建一个类&#34; .style-3&#34 ;
代码示例:
new Vue({
el: "#app",
data: function() {
return {
myArray: ['player attack', 'monster attack','player attack', 'monster attack']
}
},
computed: {
numberOfPlayers: function() {
return 2;
}
}
});
&#13;
.style-1 {
color: blue;
}
.style-2 {
color: red;
}
&#13;
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="app">
<div v-for="(item, index) in myArray" :key="item"
:class="'style-' + ((index % numberOfPlayers) + 1)"
>
{{ item }}
</div>
</div>
&#13;