margherita pizza
margherita pizza

Reputation: 7145

Vue.js how to collect values from input fields when the number of input fields aren't constant

My use case

  1. I got an array from back-end API which contains input field names.
  2. I render these names along with a input field.

This is my code.

<template>
    <div class="itemGenerate">
        <div>

            <ul>
                <li v-for="identifier in identifiers" :key="identifier">
                <input type="text" value=""/>{{identifier.name}}
                </li>
            </ul>

            <button type="button">Add</button>
        </div>

    </div>
</template>

<script>
export default {
  data() {
    return {
      identifiers: [{ name: "Flavour" }, { name: "Size" }, { name: "Color" }]
    };
  }
};

My question is

these input fields are not constant. It'll change in each and every API call (some times it's only color sometimes color,size and another new thing).

I would use v-model if I know the number of input fields, but I cannot use here because it's not predefined.

How do I achieve this using vue.js?

Upvotes: 2

Views: 114

Answers (1)

Mehari
Mehari

Reputation: 3247

try this out

<template>
    <div class="itemGenerate">
        <div>

            <ul>
                <li v-for="identifier in identifiers" :key="identifier">
                <input type="text" v-model="item[identifier.name]"/>{{identifier.name}}
                </li>
            </ul>

            <button type="button">Add</button>
        </div>

    </div>
</template>

<script>
export default {
  data() {
    return {
      item:{},
      identifiers: [{ name: "Flavour" }, { name: "Size" }, { name: "Color" }]
    };
  }
};

Upvotes: 3

Related Questions