I'm using static modules (using the method in #178), see test repo at https://github.com/garyo/vuex-problem-test.git.
I have this layout:
โโโ App.vue
โโโ main.ts
โโโ store
โโโ index.ts
โโโ modules
โย ย โโโ modB.ts
โย ย โโโ user.ts
โโโ store-accessor.ts
i.e. two modules, a store-accessor which imports those and exports the stores, and store/index.ts which imports store-accessor and exports all the stores.
This is all OK, until modB.ts needs to use some state from user.ts. I add
import { userStore } from '@/store'
to `modB.ts, which creates an import cycle:
store/index.ts -> store/store-accessor.ts -> store/modules/modB.ts -> store/index.ts
Is there any way around that?
If you _only_ need to access the other module's state (not getters or actions or mutations), this works:
In the module modB that needs to use the other module, do this:
import userModule from '@/store/modules/user'
...
get usingUserMod() {
const userStore = this.context.rootState.user as userModule
const uid = userStore.uid
// now use uid as usual
}
It works because it uses the dynamic context in the method rather than trying to get the root store when the module is loaded.
But that cast isn't really correct; userStore is not really a userModule. So if you try to call any of its methods or use any of its getters, they will fail at runtime ("userStore.setUid is not a function").
Any hints?
After doing a bunch of reading of various things, I now understand that circular imports don't always have to be avoided -- if they're managed carefully they can work fine because of the two-phase import logic ( Instantiation then Evaluation).
I updated the above repo, https://github.com/garyo/vuex-problem-test.git, with a full working example of static vuex-module-decorator modules using the the method in #178 and calling each other via properly managed circular imports.
I now know enough to help write a section of the doc for how to do this, if folks are interested. In fact I'd suggest starting with the README from my test repo: https://github.com/garyo/vuex-problem-test/blob/master/README.md
By the way I renamed my test repo above to https://github.com/garyo/vuex-module-decorators-example -- since it's an example, not a problem anymore!
Thaks @garyo, you saved my day. I'm quite new in typescript, but shouldn't static modules with communication with each other work out of the box? It seems not a problem in plain vuex.
This should be a feature of this package.
However, Vue 3 being close to release in a couple of months, it will be interesting to see how Vuex is changing on or after the release...
Most helpful comment
By the way I renamed my test repo above to https://github.com/garyo/vuex-module-decorators-example -- since it's an example, not a problem anymore!