How exactly does the spread syntax (…) work with mapGetters?
每当您要在Vuex的mapGetter助手中使用计算的getter时,都将像这样使用它:
1 2 3 4 5 | ...mapGetters([ 'getter1', 'getter2', 'etc' ]) |
我已经看到在将数组扩展为函数自变量之前使用过的spread运算符,但没有像我们在
例如,在mozilla文档中,我也找不到这种语法的示例:
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator
那里什么都没有。 这种语法在这种情况下到底是如何工作的,也许有人可以提供一些文档吗?
mapGetters和mapActions基本上是vuex提供的帮助程序,它返回一个对象,该对象的键为方法名,而值为具有定义的方法。该对象与...(对象散布算子)组合时,将其分别散布到计算对象或方法对象中的各个函数中。
例如:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | { 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
我试图用我觉得被遗漏的细节来澄清Val的回答。在您的示例中,未在"方法前"使用扩展运算符。实际发生的情况是将其应用于
您可以这样想:
1 2 3 4 5 6 | { ...{ 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
实际上,当您没有任何本地计算属性时,可以直接将
1 2 3 4 5 6 | computed: { //nothing here - no any local computed properties ...mapGetters(['cartItems', 'cartTotal', 'cartQuantity']), }, computed: mapGetters(['cartItems', 'cartTotal', 'cartQuantity']), |
以上两种功能完全相同!
但是,当您确实具有任何本地计算属性时,则需要使用扩展语法。这是因为mapGetters返回了一个对象。然后,我们需要对象传播运算符将多个对象合并为一个。
1 2 3 4 5 | computed: { localComputed () { /* ... */ }, // we use ... Spread Operator here to merge the local object with outer objects ...mapGetters(['cartItems', 'cartTotal', 'cartQuantity']), } |
您可以阅读有关在MDN中的对象文字中传播的更多信息
基本上,在这种情况下,它用来合并对象
1 2 3 4 5 6 7 | 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文档对此解释得很清楚,但不是在
它用于将对象属性合并到另一个对象。在文档中有说明。
https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Operators/Spread_operator
在