简体   繁体   English

具有多个模块的 vuex 命名空间 mapState

[英]vuex namespaced mapState with multiple modules

I must be missing something.我一定是错过了什么。 How can I use vuex mapState with multiple modules?如何将 vuex 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.据了解,除了将对象作为参数传递之外,命名空间的 mapState 还可以接受两个参数:命名空间和表示模块成员的对象名称数组。 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?但是,如果我想将第二个命名空间中的对象添加到计算中呢? eg vendor like this:例如像这样的供应商:

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

Currently I am merging both mapState like this:目前我正在像这样合并两个 mapState:

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

And then:然后:

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

It works, but it's hardly the right way to do it.它有效,但它几乎不是正确的方法。 Or is it?或者是吗?

Use the spread operator :使用扩展运算符

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

This is from the vuex docs, you can do it all within one ...mapState({}) .这是来自 vuex 文档,您可以在一个...mapState({}) Documentation 文档

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},

Edit 2019编辑 2019

You can also pass a path to your nested module and make the module references cleaner (thanks @gijswijs )您还可以将路径传递给嵌套模块并使模块引用更清晰(感谢@gijswijs

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},

You can try this if you have no too many namespaces:如果你没有太多的命名空间,你可以试试这个:

    ...mapState({
      userAddresses: 'user/addresses',
      userCreditCards: 'user/creditCards'

      vendorProducts: 'vendor/products',
      vendorRatings: 'vendor/ratings',          
    }) 

You could also use Object.assign like this.你也可以像这样使用 Object.assign 。 Similar to your current solution but a bit cleaner.类似于您当前的解决方案,但更简洁一些。

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

Make use of spread operator to access multiple module State values利用扩展运算符访问多个模块状态值

 ...mapState('user', {
     isLoggedIn: ({ activeUser }) => !!activeUser?.id
  }),
   ...mapState('quizzes', ['getCategories'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM