Wai Yan Htet
Wai Yan Htet

Reputation: 63

Emitting object or value in vue.js component child to parent communication

I would like to know which is better way to emit data to parent in vue component. From parent to child I pass prop object but from child to parent with $emit. Should I pass object or value? e.g.: { product } or product.id and also I have to reuse some data in the { product } like product.price on event listener. What should I use? Emit an object or just value then loop and condition in listener function?

Upvotes: 0

Views: 1639

Answers (2)

MathGainz
MathGainz

Reputation: 360

This does not work in case of Pass by reference. I mean it works but Vue is screaming don't mutate props directly...

Where movie is an object and genres is an array. Child components props and event

props: { genres: { type: Array, default () { return [] } } }

...

this.$emit('changeGenreList', this.genres)

I had to make the local copy of this array with slice() and then I was emitting this copy.

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

Just use a two way sync here:

@product.sync="product"

In the child:

this.$emit('update:product', product)

Whenever you make a change to the property of the product.

Upvotes: 1

Related Questions