vuex-local
Local state management within Vuex
Why?
Global state management is one of the problems on huge application development. Developers address the problem by using Flux pattern and Single Source of Truth store like Redux and Vuex. They simplify and make trackable application data flow.
However, we sometimes have to manage component local state. Because it is too complicated to manage component specific state on a global store. For addressing local state, we cannot embrace the global store advantage - trackable data flow and time-travel debugging.
vuex-local achieves simple and trackable local state management. We can define a local Vuex module in each component and it will be registered on a Vuex store. This let us use features of dev tools such as time-travel debugging for local state. In addition we can use a local module on a component in natural way.
Example
First, you have to install vuex-local for Vue.js. vuex-local can receive parentModulePath
option to specify where to register all local modules.
// store.js VueVue // generate `locals` module automatically Vuex
Then, you can define a local module on each component. The component option will have local
property that is a function returning a local module object.
The local module object is same as normal Vuex module except to have name
option. The name
option specify the local module path and the prefix for getters, actions and mutations.
In local module getters and actions, getters
, dispatch
and commit
is namespaced implicitly. In other words, we do not have to care about effects for other global modules. If you want to use root level getters, you can use them from 4th argument of each getter function or rootGetters
property of the action context.
To dispatch actions or commit mutations in the global namespace, pass { root: true }
as the 3rd argument to dispatch
and commit
.
The local modules' state, getters, actions and mutations are bound to component instance automatically. You can use them in the template or other component methods easily.
const vm = store ...Counter vmcount // 10vmhalf // 5vm // increment after 1000msvm // increment immediately
Testing with vuex-local
Testing vuex-local module can be as easy as ordinary vuex module. Just getting the module by Component.local().
// Use `call` method to inject a mock componentconst module = Applocalconst state getters actions mutations = module
A full example here:
License
MIT