在我的项目中,我使用vuex-module-decorators创建了一个小的vuex模块。但是,当尝试从模板部件中的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
发布于 2020-01-30 00:00:38
我无法评论,所以我会在这里回答。你在main.js文件中导入你的商店了吗?也许这就是问题所在。祝好运!
发布于 2021-01-13 13:43:59
由于您使用的模块是动态的,因此您必须在使用它之前对其进行注册。
this.$store.registerModule('example', Example) // Don't forget to import your module注意,在使用之前注册是很重要的,所以我建议在created()中注册它。您可以考虑添加一个条件来检查模块是否已经添加。请查看此https://github.com/vuejs/vuex/issues/833
希望这能对你有所帮助(:
发布于 2020-02-20 16:29:48
还要确保在存储的index.ts文件中导入了模块,并且在模块中将({ namespaced })设置为true。(你已经做过的事情)
文件夹结构示例:
/store
└── /modules
└── Example.ts
└── Other.ts
└── Products.ts
└── ...
└── index.tsindex.ts
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
import { Example } from './modules/Example'
import { Other } from './modules/Other'
import { Products } from './modules/Products'
export default new Vuex.Store({
modules: {
Example,
Other, // Another module.
Products // Another module.
}
})Example.ts
import { Module, VuexModule, Mutation } from 'vuex-module-decorators'
@Module({ namespaced: true })
export class Example extends VuexModule {
work = false // You don't need to specify with work: boolean as TS will know the type by itself.
@Mutation
setWorking(status: boolean) {
this.work = status
}
get isWorking() {
return this.work
}
}App.vue
<template>
<div>
first attempt: {{ $store.getters['Example/isWorking'] }}
</div>
</template>https://stackoverflow.com/questions/59967515
复制相似问题