首页 > 解决方案 > Vuex 模块装饰器:从 this.$store 访问 vuex 模块没有注册模块

问题描述

在我的项目中,我使用vuex-module-decorators. 但是当尝试直接从模板部分this.$store$store在模板部分中访问它时,它不会触发注册。

这是一个例子:

// exampleModule.ts
import { Module, getModule, Mutation, VuexModule } from 'vuex-module-decorators';
import store from '@/store';

@Module({
  dynamic: true,
  namespaced: true,
  name: 'example',
  stateFactory: true,
  store,
})
class Example extends VuexModule {
  private work: boolean = false;

  get isWorking() {
    return this.work;
  }

  @Mutation
  setWorking(status: boolean) {
    this.work = status;
  }
}

export default getModule(Example);

// App.vue
<template>

  <div> 
    first attempt: {{ $store.getters['example/isWorking'] }} // this is not working
    second attempt: {{ isWorking }} // this is not working too
  </div> 
</template>

<script lang="ts">
  import Vue from 'vue';

  export default Vue.extend({
    computed: {
      isWorking() {
        return this.$store.getters['example/isWorking'];
      }
    }
  });
</script>

我真正注册模块并使其工作的唯一方法是将其直接导入组件中,如下所示:


<script lang="ts">
  import Vue from 'vue';
  import exampleModule from '@/store/modules/example/exampleModule';

  export default Vue.extend({
    computed: {
      isWorking() {
        return exampleModule.isWorking;
      }
    }
  });
</script>

我在这里错过了什么吗?这是想要的行为吗?谢谢。

顺便说一句,我在他们的 github 存储库上打开了一个问题,但我仍然没有任何答案,所以我在这里

https://github.com/championswimmer/vuex-module-decorators/issues/190

标签: typescriptvue.jsvuexstorevuex-modules

解决方案


由于您使用的模块是动态的,因此您必须在使用前注册它。

this.$store.registerModule('example', Example) // Don't forget to import your module

请注意,使用前注册很重要,所以我建议在created(). 您可以考虑添加条件来检查模块是否已添加。看看这个https://github.com/vuejs/vuex/issues/833

希望这有帮助(:


推荐阅读