I am trying to get better understanding of what the "context" object is in Vuex.
The context object is referred to numerous times in the Vuex documentation. For example, in https://vuex.vuejs.org/en/actions.html, we have:
Action handlers receive a context object which exposes the same set of methods/properties on the store instance, so you can call context.commit to commit a mutation...
I understand how to use it, and also that we can use destructuring if we only want to use the "commit" from the context object, but was hoping for a little more depth, just so I can better understand what is going on.
As a start, I found a couple ~8.5 year old posts on the "context object" as a pattern: what is context object design pattern? and Can you explain the Context design pattern?
However, specifically to Vuex, I'd love a better understanding of:
Thank you!
subscribe(handler, { prepend: true }) The subscribe method will return an unsubscribe function, which should be called when the subscription is no longer needed. For example, you might subscribe to a Vuex Module and unsubscribe when you unregister the module.
Vuex also has a helper called mapState, which makes it easy to map your state to computed properties within your components. The mapState helper can be simplified further, making it even easier to include our state where needed.
A payload is simply the data passed to our mutation from the component committing the mutation. How do we do that ? Simple… this.$store.commit(“SET_NAME”,your_name) This snippet of code will mutate the state and set whatever value that is assigned to your_name, to the name property inside our Vuex state.
Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. WARNING. As of Vue 3.0, the getter's result is not cached as the computed property does. This is a known issue that requires Vue 3.1 to be released.
From the documentation you pointed out you can read:
We will see why this context object is not the store instance itself when we introduce Modules later.
The main idea of the context object is to abstract the scope of the current Module. If you simply access store.state
, it will always be the root state.
The context object of actions and its properties/methods are described here in the source code and also referenced in the API documentation
Here is the list:
{ state, // same as store.state, or local state if in modules rootState, // same as store.state, only in modules commit, // same as store.commit dispatch, // same as store.dispatch getters, // same as store.getters, or local getters if in modules rootGetters // same as store.getters, only in modules }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With