Vue Js - Loop via v-for X times (in a range)

前端 未结 6 1055
星月不相逢
星月不相逢 2021-01-30 04:54

How can I repeat a loop via v-for X (e.g. 10) times?

// want to repeat this (e.g.) 10 times

相关标签:
6条回答
  • 2021-01-30 05:18

    I had to add parseInt() to tell v-for it was looking at a number.

    <li v-for="n in parseInt(count)" :key="n">{{n}}</li>

    0 讨论(0)
  • 2021-01-30 05:22

    In 2.2.0+, when using v-for with a component, a key is now required.

    <div v-for="item in items" :key="item.id">
    

    Source

    0 讨论(0)
  • 2021-01-30 05:26

    I have solved it with Dov Benjamin's help like that:

    <ul>
      <li v-for="(n,index) in 2">{{ object.price }}</li>
    </ul>
    

    And another method, for both V1.x and 2.x of vue.js

    Vue 1:
    
    <p v-for="item in items | limitBy 10">{{ item }}</p>
    
    Vue2:
    
    // Via slice method in computed prop
    
    <p v-for="item in filteredItems">{{ item }}</p>
    
    computed: {
       filteredItems: function () {
         return this.items.slice(0, 10)
         }
      }
    
    0 讨论(0)
  • 2021-01-30 05:27

    The same goes for v-for in range:

    <li v-for="n in 20 " :key="n">{{n}}</li>

    0 讨论(0)
  • 2021-01-30 05:31

    You can use the native JS slice method:

    <div v-for="item in shoppingItems.slice(0,10)">

    The slice() method returns the selected elements in an array, as a new array object.

    Based on tip in the migration guide: https://vuejs.org/v2/guide/migration.html#Replacing-the-limitBy-Filter

    0 讨论(0)
  • 2021-01-30 05:37

    You can use an index in a range and then access the array via its index:

    <ul>
      <li v-for="index in 10" :key="index">
        {{ shoppingItems[index].name }} - {{ shoppingItems[index].price }}
      </li>
    </ul>
    

    You can also check the Official Documentation for more information.

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