typescript - 使用 NuxtJS 和 vuex-module-decorators 的动态 vuex 存储模块

标签 typescript vue.js vuex nuxt.js

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

我尝试关注 guide from the official nuxt websitevuex-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
  }
}

// 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-class-component

最佳答案

如果您试图让您的商店模块动态注册,那么您在 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
  }
}

关于typescript - 使用 NuxtJS 和 vuex-module-decorators 的动态 vuex 存储模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60339996/

相关文章:

javascript - 在 Typescript 中向基类添加扩展

javascript - 不断检查 cookie 是否过期的最佳实践?

asynchronous - 提高同一页面上多个 Vue 组件的性能

angular - 无法在新选项卡中订阅 Angular 应用程序中的 Observable 事件

javascript - 是否可以动态构建此功能?

javascript - 将异步等待与 Array.map 结合使用

javascript - 在 vue 中构建时添加自定义 javascript 部分

javascript - Vue.js 同一组件问题的多个实例

vue.js - "TypeError: Cannot read property ' 得到 ' of undefined", Axios, Vue.JS

javascript - Vuex Action 是否必须修改或使用存储状态?