Search code examples
javascriptvue.jsvuejs2conditional-operatorv-for

Vue v-for with range and ternary class operator


I have following code

<div class="tabs-container-block">
    <div v-for="n in tabs.length" :class="n-1 === showTab ? 'tab-title active-title' : 'tab-title'"> {{ tabs[n-1].TabTitle }}</div>   
  </div>
  `, 
  data() {
    return {
      showTab: {
        type: Number,
        default: 0
      }
    }
  },

Im trying to use the 'n' value from v-for and ternary operator to switch style classes.

Currently it is not working, how can I achieve that ?


Solution

  • showTab is object , maybe you confuse it with props:

    new Vue({
      el: '#demo',
      data() {
        return {
          showTab: {
            type: Number,
            default: 0
          },
          tabs: [{TabTitle: 'aaa'},{TabTitle: 'bbb'},{TabTitle: 'ccc'}]
        }
      }
    })
    .tab-title {
      color: green;
    }
    
    .active-title {
          color: red;
        }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="demo">
      <div class="tabs-container-block">
        <div v-for="n in tabs.length" :class="n-1 === showTab.default ? 'tab-title active-title' : 'tab-title'"> {{ tabs[n-1].TabTitle }}</div>   
      </div>
    </div>