【问题标题】:Vue alternate classes in v-forv-for 中的 Vue 替代类
【发布时间】:2017-08-18 02:05:05
【问题描述】:

我有一个数组(历史),每次按下按钮时都会推送两个项目。这两个项目在打印时需要具有不同的 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 的真实性。有没有更好的方法来解决这个问题?

【问题讨论】:

    标签: vue.js v-for


    【解决方案1】:

    解决方案 1:

    您可以使用此代码:

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

    更新 - 解决方案 2 [不使用对象]:

    您可以使用没有对象的其他解决方案:

    <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)并创建一个类“.style-3”。

    代码示例:

    new Vue({
      el: "#app",
      data: function() {
        return {
        	myArray: ['player attack', 'monster attack','player attack', 'monster attack']
        }
      },
      computed: {
        numberOfPlayers: function() {
        	return 2;
        }
      }
    });
    .style-1 {
      color: blue;
    }
    
    .style-2 {
      color: red;
    }
    <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>

    【讨论】:

    • 做得很好。除了将对象传递到数组中之外,没有其他方法吗?
    • 是的,还有另一种方法(不需要对象):查看我的答案已更新。
    • 感谢您花时间写这篇文章。很棒的信息!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 1970-01-01
    相关资源
    最近更新 更多