实际上,当您没有任何本地计算属性时,您可以直接使用mapGetters
as: 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
. 看一看,你就会明白了。