Search code examples
vue.jsvuejs2v-for

Add v-model to inputs in nested v-for loop


Let's say I have component like this:

<template>
  <div>
    <div v-for="n in 2" :key="n">
      <div v-for="i in 2" :key="i">
        <input type="number" v-model="foo[n][i]">
      </div>
    </div>
    <pre>{{ foo }} </pre>
  </div>
</template>

This render 4 inputs. Now when I enter something into this inputs for example 1 to 4 to each I would like foo to become:

[
    [1,2],
    [3,4]
]

instead I have an error

TypeError: Cannot read property '1' of undefined


Solution

  • Your error is from the fact that the n and i indexes start at 1 in the v-for

    Also for a more generic approach you could generate an array from the dimensions in your created lifecycle.

    Vue.config.devtools = false;
    Vue.config.productionTip = false;
    
    var app = new Vue({
      el: '#app',
      data: {
        x: 2,
        y: 2,
        array: []
      },
      created() {
        for (let i = 0; i < this.y; i++) {
          let row = [];
          for (let j = 0; j < this.x; j++) {
            row.push(0);
          }
          this.array.push(row);
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
    <div id="app">
      <div v-for="n in y" :key="n" style="display:flex">
        <div v-for="i in x" :key="i">
          <input type="number" v-model.number="array[n - 1][i - 1]">
        </div>
      </div>
      {{array}}
    </div>