Recently, I've been playing around with the vuex module decorator in order to maintain good TypeScript practices in my vuex stores. However, I'm facing issues when trying to access the store without encountering type definition problems.
My setup includes:
- Nuxt with 'nuxt-typescript' and 'vue2-composition-api',
- Vuex with 'vuex-module-decorator' configured with getModule for SSR,
Below is a basic example of what I am trying to achieve:
store/index.ts
import { Store } from 'vuex'
import { getModule } from 'vuex-module-decorators'
import User from './user'
import Basket from './basket'
export function useUserModule(store: Store<any>): UserModule {
return getModule(UserModule, store)
}
export function useBasketModule(store: Store<any>): BasketModule {
return getModule(BasketModule, store)
}
store/user.ts
import { Module, VuexModule, Action } from 'vuex-module-decorators'
@Module({
name: 'user',
namespaced: true,
stateFactory: true,
preserveState: true,
})
export default class UserModule extends VuexModule {
user: IUser | null = null
@Action
async doSomthingWithUser(request: object) {
console.log('Success! Called from basket module')
}
}
store/basket.ts
import { Module, VuexModule, Action } from 'vuex-module-decorators'
import { useUserModule } from '.'
@Module({
name: 'basket',
namespaced: true,
stateFactory: true,
preserveState: true,
})
export default class BasketModule extends VuexModule {
basket: IBasket | null = null
@Action
async doUserAction(request: object) {
const userStore = useUserModule(this.store)
//Property 'store' does not exist on type 'BasketModule'
userStore.doSomthingWithUser({stuff:true})
}
}
Property 'store' does not exist on type 'BasketModule'
The issue here is that this.store
does exist when I log this
!
The references I came across here use this.$store
which seems to be missing in my case.
For example: getModule(MobuleB, this.$store)
I have also attempted the conventional SSR approach in Nuxt as mentioned in the documentation decorators with ServerSideRender... but I'm facing the same situation.
Although everything seems to be working fine, my IDE is flagging an error. I am new to TypeScript and I suspect the module lacks the type definition for the store. Does anyone have a solution for assigning a definition to this.store
for ALL modules, or perhaps utilizing the global this.$store
that others seem to have access to?