我很难让我的vuex模块与NuxtJS SSR,TypeScript和vuex模块装饰器一起工作。
我试着跟踪官方nuxt网站指南和vuex模块-装饰器,但没什么效果.
这是我的密码:
// 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
}
}每当我试图访问模块中的任何内容时,这些都是未定义的.
我知道这种方法是“静态模块”。我的目标是使用动态模块,但是如果静态模块是使用NuxtJS SSR的唯一方法,那么就可以了。
任何帮助都将不胜感激。谢谢:)
编辑
我放弃了使用vuex类组件
发布于 2020-03-27 13:18:47
如果您试图让存储模块动态注册,那么您在index.ts文件中所做的操作是不正确的。
在store/index.ts中定义一个空存储
import Vuex from 'vuex'
export const store = new Vuex.Store<any>({});现在在您的商店模块中:
// 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
}
}发布于 2020-02-29 09:11:25
正在与类似的问题进行斗争,并使其与本页中的代码一起工作:https://qiita.com/yoshinbo/items/70f109db7c3de4b4a99f
发布于 2020-02-28 00:43:01
那么,您需要在已创建()生命周期钩子中调用Message()函数。
目前,按照您的代码,每当组件初始化时脚本就会启动执行,但是到那时还没有建立存储,因为在生命周期钩子中调用它会更有意义。
public created() {
get message(): string {
const commonModule = getModule(CommonModule, this.$store)
return commonModule.message;
}
}希望这能有所帮助!
https://stackoverflow.com/questions/60339996
复制相似问题