1

I'm using Vue to manage a form to add guests, each guest is an object. Form is bind to newGuest which is then used in addGuest function.

After this I need to clear/reset newGuest object and nested objects. Current solution is probably not the best since I'll need to edit newGuest in two places if it changes.

What would be the best way to achieve this? Should I do looping over properties or there is an easier way?

   new Vue({
        el: '#app',
        data: {
            newGuest: {
                name: '',
                contacts: {
                    email: '',
                    phone: ''
                },
                inviteSent: false,
                RSVP: 1,
            },
            guestList: [
                {
                    name: 'Test name',
                    contacts: {
                        email: 'test@gmail.com',
                        phone: 38099212112
                    },
                    inviteSent: true,
                    RSVP: 1,
                }
            ]
        },
        methods: {
            addGuest () {
                this.guestList.push(this.newGuest);
                this.newGuest = {
                name: '',
                contacts: {
                    email: '',
                    phone: ''
                  },
                inviteSent: false,
                RSVP: 1
                }
            },
        }

    })
.guest-form__section {
   display: inline-block; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<div id="app">
 <form @submit.prevent="addGuest" class="guest-form">
        <div class="guest-form__section"><input type="text" v-model="newGuest.name" placeholder="name"></div>
        <div
                class="guest-form__section"><input type="email" v-model="newGuest.contacts.email" placeholder="email"></div>
        <div class="guest-form__section"><input type="tel" v-model="newGuest.contacts.phone" placeholder="phone"></div>
        <div class="guest-form__section"><input type="checkbox" v-model="newGuest.inviteSent"></div>
        <div class="guest-form__section"><select v-model="newGuest.RSVP">
            <option value="1">No answer</option>
            <option value="0">Declined</option>
            <option value="2">Accepted</option>
        </select>
        </div>
        <input type="submit">
    </form>
    
    
     <pre>{{$data}}</pre>
     
     </div>
Runnick
  • 613
  • 2
  • 12
  • 30

0 Answers0