实际上,当您没有任何本地计算属性时,您可以直接将mapGetters 用作:computed: mapGetters([/*...*/],而不使用Spread Syntax ...。
computed: {
//nothing here - no any local computed properties
...mapGetters(['cartItems', 'cartTotal', 'cartQuantity']),
},
computed: mapGetters(['cartItems', 'cartTotal', 'cartQuantity']),
以上两者的作用完全相同!
但是当您确实有任何本地计算属性时,您需要传播语法。这是因为 mapGetters 返回一个对象。然后我们需要 Object Spread Operator 将多个 Object 合并为一个。
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 Docs 解释得很清楚,但不是mapGetters,而是第一件事:mapState。看一看,你就会明白了。