具有多个模块的 vuex 命名空间 mapState [英] vuex namespaced mapState with multiple modules

查看:55
本文介绍了具有多个模块的 vuex 命名空间 mapState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一定是遗漏了什么.如何将 vuex mapState 与多个模块一起使用?

I must be missing something. How can I use vuex mapState with multiple modules?

据了解,除了将对象作为参数传递之外,命名空间的 mapState 还可以接受两个参数:命名空间和表示模块成员的对象名称数组.像这样

As far as understand, besides passing an object as argument, namespaced mapState can take two arguments: namespace and an array of object names denoting the members of modules. Like this

// an imcomplete vue
export default {
   computed: mapState('user', ['addresses', 'creditCards']) 
};

但是如果我想将第二个命名空间中的对象添加到计算中呢?例如像这样的供应商:

But what if i'd like to add objects from a second namespace to computed? e.g. vendor like this:

mapState('vendor', ['products', 'ratings']) 

目前我正在像这样合并两个 mapState:

Currently I am merging both mapState like this:

let userMapState = mapState('user', ['addresses', 'creditCards']); 
let vendorMapState = mapState ('vendor', ['products', 'ratings']);
let mergedMapStates = Object.assign({}, userMapState, vendorMapState);

然后:

// an imcomplete vue
export default {
    computed: mergedMapStates
};

它有效,但它几乎不是正确的方法.或者是吗?

It works, but it's hardly the right way to do it. Or is it?

推荐答案

使用 展开运算符:

computed: {
  ...mapState('user', ['addresses', 'creditCards']),
  ...mapState('vendor', ['products', 'ratings']) 
}

这篇关于具有多个模块的 vuex 命名空间 mapState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆