Search code examples
javascriptvue.jsvuejs2vue-componentv-for

Add new properties to an object used in v-for


I want to add data (from two v-text-fields) in my product component to my data that I pass to the server. So that if the user adds the values '444' and '230' to the v-text-fields, the entry would be:

{
    "444": 230
}

So far, I have hard coded the '444' and managed to get the value '230' passed. But how do i pass both '444' and '230' according to user inputs from a v-text-field?

product.vue

<v-content>
  <v-container>
    <code>formData:</code> {{ formData }}<br />
    <v-btn color="primary"  @click="create">Save</v-btn>
    (Check console)<br />
    <v-row>
      <v-col>
        <v-text-field v-for="(value, key) in formData" :key="key"
          label="Card Type" v-model="formData[key]"
          ></v-text-field>
      </v-col>
    </v-row>
  </v-container>
</v-content>
data() {
  return {
    dialog: false,
    product: null,
    error: null,
    formData: {
      444: null,
    }
  }
},
methods: {
  async create() {
    try {
      await ProductService.create(this.formData);
    } catch (error) {
      this.error = error.response.data.message
    }
  }
}

What changes would i need to make in my component so that formData is based on user input from another v-text-field?


Solution

  • I remember your previous question. To add a new item to that basic formData hash, you would do something like this:

    <div>
       <v-text-field label="Product #" v-model="newKey"></v-text-field>
       <v-text-field label="Card Type" v-model="newValue"></v-text-field>
       <v-btn @click="$set(formData, newKey, newValue)">+</v-btn>
    </div>
    

    This uses $set to add new properties to formData.