vuex-inject
Decouple Vuex modules from each other.
Installation
$ npm install vuex-inject
Usage
;; const store = // pass 'modules' to the plugin instead of store plugins: // modules,;
Example
Let's have a look at the following simple vuex modules:
// store/modules/app.js namespaced: true getters: '0.1' ; // store/modules/rest.js namespaced: true getters: { let appVersion = rootGetters'app/version'; return `/api/`; } ; // store/index.js// ... { return Vuex;};
rest
module is coupled with app
module: we can't use it or
test it separately.
Let's rewrite rest
module with the plugin:
// store/modules/rest.js namespaced: true getters: { return `/api/`; } // $ here doesn't have any special meaning $ '' ; // store/index.js// ... { return plugins: ...params ;};
Now rest
module knows nothing about app
module and it can be tested
separately but in a more "integrated" way (through the store) than unit
tests for each function in a module config:
; ;
What's inside
The injections are quite simple. When the following module will be passed to createInjectPlugin:
namespaced: true getters: $ $ '' actions: $ {} $ {} inject: getters: $todoList: 'todo/list' state: // Note: state will be injected as getter $todoTitle: 'todo/form.title' actions: $addTodoItem: 'todo/addItem' mutations: // Note: mutation will be injected as action $mutateTodoTitle: 'todo/setTitle' ;
the module functions will be replaced with something like this:
namespaced: true getters: $ rootGetters'todo/list' $ rootStatetodoformtitle actions: $ { ; } $ { ; } ;
Conditional injection
Conditional injections may help implement dynamic feature toggles. If the module,
we are injecting from, has isInjectable
(default name) getter and its value is false
, then
all the parts injected from that module will return default (original) values,
until isInjectable
getter become true
.
Example:
// store/modules/profile.js namespaced: true state: isFeatureEnabled: false groups: 'user' 'admin' getters: stateisFeatureEnabled mutations: { stateisFeatureEnabled = value; } ; // store/modules/acl.js namespaced: true getters: getters$profileGroups >= 0 $ inject: state: $profileGroups: 'profile/groups' ; // test;
API
createInjectPlugin(options)
Creates a new instance of the plugin with the given options. The following options can be provided:
modules <Object>
: store modules config. We pass it here instead of store constructor.inject <Object>
: injection config. This config has precedence over inner module inject config.moduleField <String>
: Inner module inject config will be looked under this name. Defaults toinject
conditionalGetterName <String>
: Getter name to check to find out if conditional injection is allowed. Defaults toisInjectable
License
MIT © Denis Pobelov