Sum*_*ron 6 vue.js vue-component vuex vuejs2 vuex-modules
在几乎所有关于 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)
}
}
Run Code Online (Sandbox Code Playgroud)
这按预期工作,但是如果我们希望模块具有唯一的或用户定义的命名空间怎么办?
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'])
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这会起作用,但它没有。
为什么需要这样的东西?因为
export default {
...
computed: {
...mapState(this.namespace, ['testVar']),
...
},
...
}
Run Code Online (Sandbox Code Playgroud)
不起作用
我从veux github问题中找到了这个,它似乎满足您的需求 https://github.com/vuejs/vuex/issues/863#issuecomment-329510765
{
props: ['namespace'],
computed: mapState({
state (state) {
return state[this.namespace]
},
someGetter (state, getters) {
return getters[this.namespace + '/someGetter']
}
}),
methods: {
...mapActions({
someAction (dispatch, payload) {
return dispatch(this.namespace + '/someAction', payload)
}
}),
...mapMutations({
someMutation (commit, payload) {
return commit(this.namespace + '/someMutation', payload)
})
})
}
}
Run Code Online (Sandbox Code Playgroud)
...或者也许我们不需要这个评论提到的mapXXX助手https://github.com/vuejs/vuex/issues/863#issuecomment-439039257
computed: {
state () {
return this.$store.state[this.namespace]
},
someGetter () {
return this.$store.getters[this.namespace + '/someGetter']
}
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2897 次 |
| 最近记录: |