0
votes

I have a parent and child components ShowreelApp.vue and Showreel.vue. I am passing properties over to the child when I create it.

    <showreel-component
        v-for="showreel in showreels"
        v-bind="showreel"
        :key="showreel.id"
        @update="update"
        @delete="del"
    ></showreel-component>

I then use the props to populate an update form in each child showreel.

        <div class="showreel-input">
            <label>Heading</label>
            <input type="text" :value="myHeading" >
        </div>

In the child form I am emiting an update event to the parent component to update the specific showreels data.

update(event) {
    this.$emit('update', this.id, this.heading, this.subheading, this.youtubeid);
}

When the user clicks on the update button on the child Showreels components form I would like to send the data to the parent. However I cannot bind the data to the child's input field as that causes the warning about mutating the property as I should not be updating the value from the child form.

One option I thought of was creating duplicates of each value in the child ... Updating them to the passed in props when its created , binding them to the form inputs... and then passing these values over to my parent using emit when updating.

But then these seems a bit convoluted to me and now I am thinking I have gone about this the wrong way. Any suggestions would be appreciated.

2

2 Answers

1
votes

Mutating props from a child is usually not a very good practice but if you need it, as of version 2.3+ there is a .sync modifier. For more reference see Sync modifier

Another solution is to use event emitting or VueX. I would personally recommend Vuex but if you have relatively small application go with either sync or event emitting as you have described.

0
votes

I should have mentioned that each showreel component has its own form fields and update button.

The solution I have come up with is to create a "sync" event in the parent and emit to it from the child

sync(id, property,value){
   var currentShowreel = this.showreels.find(showreel => showreel.id === id);
            currentShowreel[property] = value
},

The sync event calls a method in the parent which takes in and ID proprty name and property value.

This generic method is called from the child element inputs with a method

@keyup="sync('heading', $event.target.value)"

This calls a method in the child which in turn updates the parents data

},sync(property, value){
    this.$emit('sync', this.id, property, value);
}

Then when the user updates I simply emit the update event to the parent. The parent grabs the particular showreel items data and updates based on the latest values. It's working but not sure this is the right way of doing this.