Suzy
Suzy

Reputation: 261

Can a Parent and Child listen to same event and merge data together - Vue?

If I have a button in the parent class, and a child class stores certain data. The parent class also stores different data.

When we click on the parent's button, is it possible for the child class to listen to this event and then pass this data into the parent, then the parent also grabs its own data and merge this data together?

How can they both listen to the same button event, and then retrieve data and pass data to one another? The data needs to be passed through another function to format/change the values too, not just displaying this data.

Is this possible and how, since this button seems to affect two components and data is passed along?

Thanks!

Upvotes: 0

Views: 170

Answers (1)

bbsimonbb
bbsimonbb

Reputation: 29002

Children cannot catch parents' events. Children can expose methods that parents can call, or you can create a reactive property that represents whatever state changes when the parent button is clicked.

Events are messy and low level and you shouldn't mourn not being able to use them. Using state and reactivity is much cleaner. Vue components should really only store "private" state. Props are available for passing state down to immediate children. It's much better to extract state into a) a plain old javascript object, passed around via data or provide/inject, or b) vuex, then watch reactivity work its magic.

When you define your data, you can reference anything anywhere. So if you create an object in global scope, let's call it $myState...

Vue.prototype.$myState = { myProp: "hello", myName: "Simon"}

then you can reference it in your data in any component...

data : function(){return { myState : this.$myState }

Some people will object that doing this creates spaghetti - anything anywhere can modify your global state object, but for many many applications, the simplicity gained by "normalizing" state and storing it centrally will outweigh the costs.

Upvotes: 1

Related Questions