带有 NuxtJS 和 vuex-module-decorators 的动态 vuex 存储模块

Atl*_*ybe 6 typescript vue.js vuex nuxt.js

我很难让我的 vuex 模块与 NuxtJS SSR、TypeScript 和 vuex-module-decorators 一起工作。

我尝试遵循官方 nuxt 网站vuex-module-decorators 的指南,但没有任何效果......

这是我的代码:

// 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
  }
}
Run Code Online (Sandbox Code Playgroud)
// store/index.ts
import Vuex from 'vuex'
import CommonModule from '~/store/CommonModule'

export function createStore() {
  return new Vuex.Store({
    modules: {
      CommonModule,
    },
  })
}
Run Code Online (Sandbox Code Playgroud)
// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

每当我尝试访问模块中的任何内容时,这些都是未定义的...

我知道这种方法是“静态模块”。我的目标是使用动态模块,但如果静态模块是使用 NuxtJS SSR 进行这项工作的唯一方法,那就没问题了。

任何帮助将不胜感激。谢谢 :)

编辑
我放弃并使用vuex-class-component

小智 5

如果您尝试使商店模块动态注册,那么您在 index.ts 文件中所做的操作是不正确的。

在 store/index.ts 中定义一个空商店

import Vuex from 'vuex'

export const store = new Vuex.Store<any>({});

Run Code Online (Sandbox Code Playgroud)

现在在您的商店模块中:

// 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
  }
}

Run Code Online (Sandbox Code Playgroud)


Var*_*tel 1

那么,您需要在created() 生命周期挂钩内调用Message() 函数。

目前,根据您的代码,只要组件初始化,脚本就会开始执行,但那时存储尚未设置,因此在生命周期挂钩内调用它会更有意义。

public created() {
  get message(): string {
    const commonModule = getModule(CommonModule, this.$store)
    return commonModule.message;
  }
}

Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!