xTheWolf
xTheWolf

Reputation: 1886

VueJS: Forms in v-for - How to get the correct data?

So in a table I'm displaying multiple "Reservations" using Vue.js & v-for.

Each row in the table has a form which consists of this:

<tr v-for="reservation in reservations" :key="reservation.id">
            <td>
                <form @submit.prevent="sendAnswer" method="post" >
                    <select name="reservationResponse" id="reservationResponse" v-model="selected">
                        <option value="invalid">-- Select Answer --</option>
                        <option value="confirm">Confirm</option>
                        <option value="full">Full</option>
                        <option value="closed">Closed</option>
                        <option value="remove">Remove without E-Mail</option>
                    </select>
                    <br><br>
                    <input type="submit" class="btn btn-blue btn-sm" value="Send answer">
                </form>
            </td>
</tr>

Now, when I press one of the submit buttons how can I get the correct reservation associated with the form from my reservations array?

e.g.: I want to send a post request updating the status of the respective reservation. Therefor, I need the id and the option value of the selected reservation.

Upvotes: 1

Views: 3342

Answers (1)

anon
anon

Reputation:

Traditionally, you need to apply a v-model to your select so that you can read the data. Create a variable in data() (such as reservationResponseSelection in this example), and then on the select itself add v-model="reservationResponseSelection". The variable will be [reactive][1], and update when you select a new option. You can then read that data in your sendAnswer method.


As you are using a v-for to generate this data, you will need create a unique variable for each select. You can do this by using the unique data that is passed into the loop. For example you could use the reservation.id (the same one that you're using for the :key).

In your data() you would do:

data() {
  reservationOptions: {}
},```

and then on your `select` you would add: `v-model="reservationOptions[reservation.id]"`

This then gives you an object with your reservation values corresponding to each ID inside it.


  [1]: https://v2.vuejs.org/v2/guide/reactivity.html

Upvotes: 3

Related Questions