Search code examples
vue.jshtml-selectv-for

How do I bind each select option for each item in for loop? Vue.js


So I have the following code in vue.js:

<div v-for="guest in guests" :key="guest">
  <label for="attendance">Will  {{guest}}  be attending? </label>
    <select v-model="attendance">
      <option value="yes">Yes</option>
      <option value="no">No</option>
    </select>
    <br><br>
</div>

Current Output

I want to know what each guest selects and send it to my backend. Guest is an array that gets sent from the previous page. Here is it's code:

created() {
  this.guests = this.$route.query.guests;
  this.numGuests = this.guests.length;
},

Currently I am just sending each guest by sending this.guest but I am hoping to bind this somehow. I have no idea how to do this and I do not know if I am searching for the right thing either. Hopefully someone can help me.


Solution

  • you could save it like an object like this

       new Vue({
          el: '#app',
          data: {
            guests: [
              'steve', 'mark', 'mario'
            ],
            attendance: {}
          }
        })
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
    <div id="app">
      <div v-for="guest in guests" :key="guest">
        <label for="attendance">Will  {{guest}}  be attending? </label>
        <select v-model="attendance[guest]">
          <option value="yes">Yes</option>
          <option value="no">No</option>
        </select>
        <br>
      </div>
      
      <h2>Attendace: {{ attendance }}</h2>
    </div>