DEV Community

loading...

Discussion on: Watch for Vuex State changes!

Collapse
allen1556 profile image
Allen

Easy to understand and cater the solution to match my specific situation. One note though: I'm using Vuex as a substitute for event emitters and since my state values might not always be changing I had to use the vuex subscribe as watchers only respond to changes.

On that, it seems that Vuex can be really useful when trying to extend the functionality of event emitters; is this a recommended practice?

For example, I'm creating a simple showcase of UI elements and I have a form. The elements that make up the form would essentially be firing off events when they are clicked/modified/etc. As far as I can tell, using event emitters, the only way to respond to these events is to use v-on:<event name> on all of the parent elements. Given this:

That would mean putting @:btnClick="<fxn>" on every element. That just seems inefficient. This use-case is not ideal, but given an application that has a lot of large forms responding to events on every parent and then propagating it up seems like it could be a mess.

TLDR:

If I have a generic button component that I want to fire off a function that is held in a specific vue page, would using the button to modify the application vuex state be a good practice?

Thanks!

Collapse
viniciuskneves profile image
Vinicius Kiatkoski Neves Author

Hey @allen1556 , first of all thanks for the kind feedback!

Well, I will try my best to understand your issue and help you.

I think you're concern about adding some logic to your button, am I right? From what I understood you want to keep it "pure", which means that is just emits an event and the parent handles it the way it wants but as you've just shown, you might have 10x this button and have to add the props (which are different for each button) + the same handler over and over, right?

If I got it right, adding the handler to your button component might not allow you to use in other places. What you can do is to have a wrapper that handles this event (the wrapper forwards everything down to the component). The @click would just dispatch your action for example. So, short answer, yes, it is fine to update your state like that. The wrapping component would have this "store" logic and would make sense just on this part of your application and your button would still work anywhere else you need.

Did I get your idea right?

If not, please, let me try it again 😅