typescript - 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
解决方案
由于您使用的模块是动态的,因此您必须在使用前注册它。
this.$store.registerModule('example', Example) // Don't forget to import your module
请注意,使用前注册很重要,所以我建议在created()
. 您可以考虑添加条件来检查模块是否已添加。看看这个https://github.com/vuejs/vuex/issues/833
希望这有帮助(:
推荐阅读
- django - 在 Django 的单个 for 循环中从两个查询中渲染对象
- sql - 如何在 SQL 中过滤和计算百分比和计数
- node.js - Docker compose - 无法连接到 mysql - 应用程序在 mysql 之前构建?
- javascript - Javascript GET 重定向 URL
- python - Pandas 分配未按预期更改 Dataframe
- javascript - 在 npm run build 之前检查 jshint 错误
- python - button.clicked.connect 时在函数之间传递变量
- github-actions - github-action:IF 有 ELSE 吗?
- ios - 为什么会出现错误:类与键名的键值编码不兼容?
- mysql - 多个选择语句在mysql中给出错误的输出