有什么方法可以简化Vuex模块的访问?
从此:
this.$store.dispatch('moduleA/save')
this.$store.getters['moduleB/someGetter']
对此:
this.$store.moduleA.dispatch('save')
this.$store.moduleB.getters['someGetter']
有什么方法可以简化Vuex模块的访问?
从此:
this.$store.dispatch('moduleA/save')
this.$store.getters['moduleB/someGetter']
对此:
this.$store.moduleA.dispatch('save')
this.$store.moduleB.getters['someGetter']
您是否看过map*
助手?它们使您可以将状态,吸气剂,突变和操作作为常规属性直接导入到组件中。
import { mapGetters,mapActions } from 'vuex'
export default {
computed: {
...mapState('moduleB',[
'someGetter'
])
},methods: {
...mapActions('moduleA',[
'save'
]),test() {
// Same as this.$store.dispatch('moduleA/save')
this.save()
// Same as this.$store.getters['moduleB/someGetter']
this.someGetter
}
}
}
除此之外,您提出的语法是不可能的,但是没有什么可以阻止您编写自己的辅助函数来简化其使用。
如果您真的想要您建议的语法,则可以像这样(未经测试)破解它:
function createModuleProxy(store,module) {
return {
state: new Proxy({},{
get(target,prop) {
return store.state[module][prop]
},set(target,prop,value) {
store.state[module][prop] = value
return true
},}),getters: new Proxy({},prop) {
return store.getters[module + '/' + prop]
},dispatch(mutation,payload) {
return store.dispatch(module + '/' + mutation,payload)
},commit(action,payload) {
return store.commit(module + '/' + action,payload)
}
}
}
store.moduleA = createModuleProxy(store,'moduleA')
store.moduleB = createModuleProxy(store,'moduleB')
store.moduleA.dispatch('save')
store.moduleB.getters['someGetter']