How to limit iteration of elements in `v-for`

前端 未结 3 497
一整个雨季
一整个雨季 2020-12-08 02:10

I\'m building a small application in Vuejs 2.0 I\'m having approx 15 iterating elements I want to limit the v-for for only 5 elements and can have

相关标签:
3条回答
  • 2020-12-08 02:47

    You can try this code

    <div v-if="showLess">
      <div v-for="value in array.slice(0, 5)"></div>
    </div> 
    <div v-else> 
      <div v-for="value in array"></div>
    </div> 
    <button @click="showLess = false"></button>
    

    You will only have 5 elements in the new array.

    Update: Tiny change that makes this solution work with both arrays and objects

    <div v-if="showLess">
      <div v-for="(value,index) in object">
        <template v-if="index <= 5"></template>
      </div>
    </div> 
    <div v-else> 
      <div v-for="value in object"></div>
    </div> 
    <button @click="showLess = false"></button>
    
    0 讨论(0)
  • 2020-12-08 02:50

    you can try this solution to...

    <div  class="body-table  div-table" v-for="(item,index) in items"  :key="item.id" v-if="items && items.length > 0 && index <= limitationList">....
    

    and set your limit in data

    data() {
      return {
        limitationList:5
      };
    },
    

    and set a function in you btn

      <button  @click="updateLimitation(limitationList)">
        show {{limitationList == 5 ? 'more' : 'less'}}
      </button>
    

    and this your methods

    updateLimitation(limitationList){
      if (this.limitationList == this.items.length) {
        this.limitationList = 5
      }else{
        this.limitationList = this.items.length
      }
    }
    

    i hope useful for you...

    0 讨论(0)
  • 2020-12-08 02:53

    Am i too late? You can solve this using computed properties:

    <div v-for="value in computedObj">{{value}}</div>
    <button @click="limit = null">Shore more</button>
    

    Then in your data:

    data(){
      return {
        object:[], // your original data
        limit: 5 // or any number you wish to limit to
      }
    }
    

    And finally in your computed properties:

    computed:{
      computedObj(){
        return this.limit ? this.object.slice(0,this.limit) : this.object
      }
    }
    

    When your click the button, the limit is cleared and the whole data is shown/returned

    0 讨论(0)
提交回复
热议问题