Vuex 3
Published on Dec 2, 2021
Source
Introduction
- state management pattern + library for Vue
- for medium to large scale SPA
- solve problems
- multiple views depending on same piece of state
- actions from different views need to mutate the same piece of state
- reactive
- can only mutate state through commiting mutations
Core Concepts
State
- single state tree, so one store for each application
- provide
store
in root instance to inject store into all child components. Can be access throughthis.$store
mapState
is for mapping multiple store state properties ('count' = mapthis.count
tostore.state.count
)- spread it when use with local computed properties
Getters
- like computed property for store. When we need to value from computing a state
- evaluate based on dependencies
- access via
this.$store.getters
- arguments:
state, getters?
- method-syle allows passing arguments to getter
- spread
mapGetters
in computed
Mutations
- only way to change state
- has a
type
and ahandler
(perform actual state modification) store.commit(<type>, payload?)
ORstore.commit(type: <type>, <payload>: value)
. payload should be an object- follows reactivity rules
- initial state
Vue.set
OR replace the whole object
- constant for type in large project
- must be synchronous
mapMutations
Actions
- commit mutations
- can be asynchronous
- receive
context
object and alsopayload?
store.dispatch
mapActions
- can
then
ondispatch
to chain actions
Modules
- each module can has its own store, even nested modules
- local state is the first argument.
- actions has
context.state
andcontext.rootState
(arguments:state, commit, rootState?, rootGetters?
). Same thing for getters - actions, mutations, and getters are registered under the global namespace. Use
namespace:true
to registers them under module - pass
{root: true}
as third argument todispatch
andcommit
to trigger actions in the global namespace - can register global actions in namespaced module using
handler
and{root:true}
- can pass module namespace when mapping to save keystrokes OR
createNamespaceHelpers
- look out for namespace when developing plugin
store.registerModule
to register a module after store is created. CanunregisterModule
andhasModule
preserveState
Advanced
Application Structure
- store has the application-level state
- only mutate using mutation and keep it sync
- use actions to do async stuff
Plugins
plugins
when creating store- a function that only receives
store
Strict Mode
strict:true
- do not enable for production because can be expensive
Form Handling
- bind value and
@input
ORget
andset
Testing
- mutation: export mutation itself
- action: mock
- getter: same as mutation
Hot Reloading
- supports hot-reloading mutations, modules, actions and getters during development