Vue v-用于条件样式

时间:2018-06-08 18:48:26

标签: vue.js vuejs2

我使用v-for创建按钮。如果isActiveButton()返回true,我会添加.active类:

<button 
  v-for="(text, index) in this.buttonOptions" 
  class="btn" 
  :class="{active: isActiveButton(text)}" 
  :value='text' 
  @mousedown.prevent @click="some_method">
    {{text}}
</button>

如果isActive()所有 false返回buttonOptions,将.active类添加到第一个按钮的最佳方法是什么?请注意,buttonOptions是道具。

2 个答案:

答案 0 :(得分:2)

A Computed Property将是最佳选择!

&#13;
&#13;
var app = new Vue({
  el: '#app',
  data: {
    buttonOptions: ['button1', 'button2', 'button3', 'button4']
  },
  methods: {
    isActiveButton: function (text) {
      return (text === text.toUpperCase());
    },
    some_method: function() {
      console.log('Button clicked')
    }
  },
  computed: {
    shouldFirstBeActive: function () {
      return (this.buttonOptions.filter(el => this.isActiveButton(el))).length === 0
    }
  }
});
&#13;
.active {
  background: #f00;
}
&#13;
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <section>
    <button 
      v-for="(text, index) in buttonOptions" 
      class="btn" 
      :class="{active: isActiveButton(text) || (shouldFirstBeActive && index === 0)}" 
      :value='text' 
      @mousedown.prevent @click="some_method">
        {{text}}
    </button>
  </section>
</div>
&#13;
&#13;
&#13;

我不知道方法isActiveButton做了什么,所以我不得不即兴发挥:它检查字符串是否为大写。

如果shouldFirstBeActive数组中的所有项都未通过true方法,则返回buttonOptions的计算属性isActiveButton的作用是什么:

return (this.buttonOptions.filter(el => this.isActiveButton(el))).length === 0  

例如,如果您将button2更改为BUTTON2,那么isActiveButton会返回该项目的true,这会将shouldFirstBeActive计算的属性呈现为false

&#13;
&#13;
var app = new Vue({
  el: '#app',
  data: {
    buttonOptions: ['button1', 'BUTTON2', 'button3', 'button4']
  },
  methods: {
    isActiveButton: function (text) {
      return (text === text.toUpperCase());
    },
    some_method: function() {
      console.log('Button clicked')
    }
  },
  computed: {
    shouldFirstBeActive: function () {
      return (this.buttonOptions.filter(el => this.isActiveButton(el))).length === 0
    }
  }
});
&#13;
.active {
  background: #f00;
}
&#13;
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
  <section>
    <button 
      v-for="(text, index) in buttonOptions" 
      class="btn" 
      :class="{active: isActiveButton(text) || (shouldFirstBeActive && index === 0)}" 
      :value='text' 
      @mousedown.prevent @click="some_method">
        {{text}}
    </button>
  </section>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用计算过滤this.buttonOptions,其中isActiveButton为true,并将index作为参数