Home > Back-end >  Vue JS taking input dynamically inside v-for
Vue JS taking input dynamically inside v-for

Time:11-05

Hi I am trying to taking input in this fashion:

itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}]

As the user presses add button new input fields get added.
For this I have taken an empty array=> itemPrices: [], inside vue app data.
Now Inside table element I have this code:

<vs-tr v-for="n in num" v-bind:key="n">
                <vs-td
                  ><vs-input
                    v-model="itemPrices[n].regionId"
                    placeholder="Region Name"
                /></vs-td>
                <vs-td>
                  <vs-input
                    placeholder="price"
                    v-model="itemPrices[n].price"
                  />
                </vs-td>
              </vs-tr>

Here 'num' is just an integer which decides how many rows should be there. But this is not working... What is a possible solution for this task?

CodePudding user response:

If you are sure “num” is a filled array I think you can use the following code:

<vs-tr v-for="n in num" v-bind:key="n">
            <vs-td
              ><vs-input
                v-model="n.regionId"
                placeholder="Region Name"
            /></vs-td>
            <vs-td>
              <vs-input
                placeholder="price"
                v-model="n.price"
              />
            </vs-td>
          </vs-tr>

Since n is a representation of each instance inside your array.

Although, you should provide you JS code as well. This way people here get a better understanding of what is going on. For example, I can’t see what “num” looks like.

CodePudding user response:

If I understood you correctly, you set num as itemPrices array length:

new Vue({
  el: '#demo',
  data() {
    return {
      itemPrices: []
    }
  },
  computed: {
    num() {
      return this.itemPrices.length
    }
  },
  methods: {
    addItem() {
      this.itemPrices = [...this.itemPrices, {regionId: "", price: ""}]
    }
  }
})
<link href="https://unpkg.com/[email protected]/dist/vuesax.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuesax.min.js"></script>
<div id="demo">
  <vs-button @click="addItem">add</vs-button>
  <vs-tr v-for="(n, i) in num" :key="n">
    <vs-td>
      <vs-input
        v-model="itemPrices[i].regionId"
        placeholder="Region Name"
      />
    </vs-td>
    <vs-td>
      <vs-input
        placeholder="price"
        v-model="itemPrices[i].price"
      />
    </vs-td>
  </vs-tr>
</div>

  • Related