【发布时间】:2019-07-02 18:49:09
【问题描述】:
在我看到的关于 vuex 模块注册的几乎所有指南、教程、帖子等中,如果模块是由组件注册的,则 createNamespacedHelpers 会在 export default 组件语句之前导入和定义,例如:
import {createNamespacedHelpers} from 'vuex'
const {mapState} = createNamespacedHelpers('mymod')
import module from '@/store/modules/mymod'
export default {
beforeCreated() {
this.$store.registerModule('mymod', module)
}
}
这按预期工作,但是如果我们希望模块具有唯一的或用户定义的命名空间怎么办?
import {createNamespacedHelpers} from 'vuex'
import module from '@/store/modules/mymod'
export default {
props: { namespace: 'mymod' },
beforeCreated() {
const ns = this.$options.propData.namespace
this.$store.registerModule(ns, module)
const {mapState} = createNamespacedHelpers(ns)
this.$options.computed = {
...mapState(['testVar'])
}
}
}
我认为这会起作用,但它没有。
为什么需要这样的东西? 因为
export default {
...
computed: {
...mapState(this.namespace, ['testVar']),
...
},
...
}
没用
【问题讨论】:
-
遇到了类似的问题,尝试从商店访问动态命名空间项目,我发现了另一种解决方法:我使用:
computed: { testVar(){ return this.$store.state[this.namespace].testVar; } }而不是不工作的computed: { ...mapState(this.namespace, ['testVar']), },而不是:computed: { testVar(){ return this.$store.state[this.namespace].testVar; } }
标签: vue.js vuejs2 vue-component vuex vuex-modules