24

每当您想将计算的 getter 与 Vuex 的 mapGetter 助手一起使用时,您可以像这样使用它:

...mapGetters([
    'getter1', 
    'getter2', 
    'etc'
])

我已经看到之前使用扩展运算符来扩展数组以用作函数参数,但不是在我们在mapGetters示例中看到的方法前面。

例如,在查看 mozilla 文档时,我也找不到这种语法的示例:

https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator

什么都没有。这种语法究竟是如何工作的,这种情况下,有人可以提供一些关于这方面的文档吗?

4

4 回答 4

27

mapGetters 和 mapActions 基本上是 vuex 提供的一个帮助器,它返回一个对象,其中键作为方法名称,值作为具有定义定义的方法。当与 ...(对象扩展运算符)结合使用时,此对象将其分别扩展为计算对象或方法对象中的各个函数。

例如:-

{
    computed: {
        ...mapGetters([
            'getter1',
            'getter2',
            'getter3'
        ]);
    }
}

{
    computed: {
        getter1() {
            return this.$store.getters.getter1;
        },
        getter2() {
            return this.$store.getters.getter2;
        },
        getter3() {
            return this.$store.getters.getter3;
        },
    }
}

以上两者是相同的,因此基本上它会返回一个定义对象 {getter1, getter2, getter3} 并分成具有相同名称的各个计算属性。

您还可以参考这些网址:-

https://www.youtube.com/watch?v=SaBnaGu7cP8&list=PL4cUxeGkcC9i371QO_Rtkl26MwtiJ30P2&index=8

https://vuex.vuejs.org/en/getters.html

于 2018-01-07T13:49:50.447 回答
5

我试图用我觉得被省略的细节来澄清 Val 的回应。在您的示例中,没有在“方法前面”使用扩展运算符。实际发生的是它被应用于结果mapGetters

你可以这样想:

{
    ...{
        getter1: /* a mapped fn from vuex store */,
        getter2: /* a mapped fn from vuex store */,
    }
}

您可以阅读 Val Cajes Luminarias 提供的文档,了解有关扩展运算符如何与对象文字一起使用的更多详细信息。https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator

于 2018-01-04T17:03:56.503 回答
2

实际上,当您没有任何本地计算属性时,您可以直接使用mapGettersas: computed: mapGetters([/*...*/]without Spread Syntax 。...

computed: {
//nothing here - no any local computed properties
      ...mapGetters(['cartItems', 'cartTotal', 'cartQuantity']),
    },

computed: mapGetters(['cartItems', 'cartTotal', 'cartQuantity']),

以上两者都做完全相同的事情!

但是当你确实有任何本地计算属性时,你需要传播语法。这是因为 mapGetters 返回一个对象。然后我们需要对象扩展运算符将多个对象合并为一个。

computed: {
  localComputed () { /* ... */ },
  // we use ... Spread Operator here to merge the local object with outer objects
  ...mapGetters(['cartItems', 'cartTotal', 'cartQuantity']),
}

同样的情况发生在mapActions, mapState

您可以在MDN中阅读有关在对象文字中传播的更多信息

基本上,在这种情况下,它用于合并对象

let obj = {a: 1, b: 2, c: 3}
let copy = {...obj}
// copy is {a: 1, b: 2, c: 3}

//without ..., it will become wrong
let wrongCopy = {obj}
// wrongCopy is { {a: 1, b: 2, c: 3} } - not what you want

实际上,Vuex 文档对此进行了非常清楚的解释,但不是在mapGetters第一件事中:mapState. 看一看,你就会明白了。

于 2020-05-10T03:06:40.767 回答
2

它用于将对象属性合并到另一个对象。它在文档中有说明。 https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator

节下Spread in object literals

于 2018-01-04T09:17:46.657 回答