I'm having a hard time making my vuex modules work with NuxtJS SSR, TypeScript and vuex-module-decorators.
I tried following guide from the official nuxt website and the vuex-module-decorators, but nothing works...
Here's my code :
// store/CommonModule.ts
import { Module, VuexModule, Mutation } from 'vuex-module-decorators'
@Module({
name: 'CommonModule',
namespaced: true,
stateFactory: true,
})
export default class CommonModule extends VuexModule {
message: string = 'hi'
@Mutation
public SET_MESSAGE(val: string) {
this.message = val
}
}
// store/index.ts
import Vuex from 'vuex'
import CommonModule from '~/store/CommonModule'
export function createStore() {
return new Vuex.Store({
modules: {
CommonModule,
},
})
}
// components/Home.vue
import { Component, Vue } from 'vue-property-decorator';
import { getModule } from 'vuex-module-decorators';
import CommonModule from '~/store/CommonModule'
@Component
export default class Home extends Vue {
get message(): string {
const commonModule = getModule(CommonModule, this.$store)
return commonModule.message // throws an error: Cannot read property 'message' of undefined
}
}
Whenever I try to access anything in my modules, these are undefined...
I know this approach is "static modules". My goal is to use dynamic modules, but if the static modules are the only way to make this work with NuxtJS SSR, it'll be fine.
Any help will be greatly appreciated. Thanks :)
EDIT
I gave up and used vuex-class-component
What your doing in your index.ts file is incorrect if your trying to make your store modules register dynamically.
Define an empty store in store/index.ts
import Vuex from 'vuex'
export const store = new Vuex.Store<any>({});
Now in your store modules:
// store/CommonModule.ts
import { Module, VuexModule, Mutation } from 'vuex-module-decorators'
// import the empty store
import store from '.'
@Module({
name: 'CommonModule',
namespaced: true,
stateFactory: true,
// add this
dyamic:true,
store
})
export default class CommonModule extends VuexModule {
message: string = 'hi'
@Mutation
public SET_MESSAGE(val: string) {
this.message = val
}
}
Was fighting with a similar problem and got it to work with code from this page: https://qiita.com/yoshinbo/items/70f109db7c3de4b4a99f
Well, you need to call the Message() function inside of the created() lifecycle hook.
Currently as per your code, script starts the executing whenever component is Initialise but by that time store has not been in set up due to which calling it inside lifecycle hooks would make more sense.
public created() {
get message(): string {
const commonModule = getModule(CommonModule, this.$store)
return commonModule.message;
}
}
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With