Search code examples
vue.jsvuejs2v-for

vue.js v-for iterate variable number of times


I would like to iterate rows in a table based over a range. But all examples I've seen show how to do this for a constant for example,

<div>
  <span v-for="n in 10">{{ n }} </span>
</di

How can I do this for a variable similar to this,

<table>
   <tr v-for="(el, index) in form.repeat" :key="index">
      <td>hello</td>
   </tr>
</table>

This variable form.repeat is set in a form on the page.

Thanks


Solution

  • I had this issue week, my workaround for it was setting a variable in your data section to the number of rows you want. In my case based on the number of devices my backend returned the length of the list as part of the response. When Vue receives this response. I assign the variable that I created earlier in my data section to this number and I plug that into my v-for loop.

    enter image description here

    In the data section:

    data: () => ({'num_pis': 0})
    

    In the template part, reference the number. This is just a snippet, I'm using a v-data-table from Vuetify.

    <template slot="items" slot-scope="props">
      <td class="table-content-style">{{ props.item.metric_name }}</td>
      <td v-for="i in num_pis">
        {{ props.item[i] }}
      </td>
    </template>
    

    Codepen Example