vuex-typesafe
ATTENTION: THIS PROJECT IS EXPERIMENTAL. DO NOT USE IN COMMERCIAL CODE!
This is a simple way to make Vuex typescript-ready. To type your store/module, you have to declare actions, mutations and getters like this:
Actions
Mutations
Getters
SubModules
If your store / module has submodules you can type it this way:
Notice: MySubModuleData1
and MySubModuleData2
are example module data types created with the following method.
ModuleData
To create the module data type do this:
;
By default, all modules are namespaced. You have to explicitly declare your module non namespaced like this
;
If your getter handlers or action handlers depend on the store's root, you can do it typeesafe:
;
Notice: MyStoreData
is the store data type which is created exactly like a module data type.
Now that you have created the module data type, you can program the module.
Class-Based Modules
You can write class-based modules like this
;
Notice: Your helper methods must be declared private, everything else must be public and actions and mutations must have their respective decorators.
Also keep in mind, that there are access restrictions for your methods
- Getter Methods can only access other getters, fields, the root object and those private methods accessing only these
- Mutation methods can only access fields and those private methods accessing only these
- Action methods can access all methods, fields, the root object and private methods
- Private methods can access all methods, fields and the root object
Violating these access restrictions will result in an Exception at runtime!
Store
To create and use the store with typesafety you have to do the following:
;;;new Vue
To use it in your components you have to declare the store type like this
The typesafe store works exactly like the vuex store with one exception. To access operations of namespaced modules you have to do this
this.$store.myNamespacedModule.commit'myOperation', myPayload; //typesafe (won't compile with wrong string or payload)
instead of this
this$store;
The same holds for accessing getters and actions of namespaced modules.