VueX is based on Facebook Flux architectural patterns
So what is Flux?
model provides state to view
view updates model
action creator creates an action
action is dispatched using dispatcher
store holds application state
view is rendering sate to the user
illustrations by https://code-cartoons.com/
illustrations by https://code-cartoons.com/
vue add vuex
vue add vuex
Store state should be accessed in a component computed property since store state is reactive
store is automatically injected by Vue when using Vue.use(VueX)
Even though you have access to state - never change it from the component
Similar to computed of the component, if we need to derrive state based on store dependencies, we use getters in the store and access them as this.$store.getters in the component
you get access to both state and store getters
And the cool part is that we can return a function from getter to pass arguments from the component
State should be changed ONLY by committing mutations
commit accepts a mutation name and payload
You can also use object syntax for committing mutations
Mutation are synchronous, so no async logic in your mutations
Mutations can be commited in components but it's advised not to
use constants for mutation types
Actions don't mutate the state but rather commit mutations
actions can include asynchronous code
actions are dispatched using $store.dispatch('actionName', payload) or similar to mutations having object syntax
Convert ToDo app to use VueX
For managing async flows when one action needs to fire after other, we can return a Promise from an action
For managing async flows when one action needs to fire after other, we can return a Promise from an action
import { mapState } from 'vuex'
State
import { mapGetters, mapMutations } from 'vuex'
getters, mutations
array notation to map 1 to 1
If you want to map to different name
import { mapGetters, mapMutations } from 'vuex'
array notation to map 1 to 1
If you want to map to different name
we can separate VueX state by using modules.
module has encapsulated state, but will have access to rootState through context
module has encapsulated state, but will have access to rootState through context
actions, mutations and getters inside modules are still registered under the global namespace unless provided namespace: true option
In strict mode any mutations outside of handlers will trigger a warning
Create VueX store with user and module and posts module
Load posts into a store on initial app load
Change posts access to be getters from the store
Integrate login flow with VueX user module
Add login button to redirect to the Login page or present user name when the user is logged in
create add comments functionality to an app (if not logged in, it should be a guest, if logged in, should write user name near the comment)
When filling the login form, log in to dummy API, store user in store and redirect to UserProfile page.