Vuex 中的三个句点语法?

Three periods syntax in Vuex?

我不太清楚 mapstate 的作用,除此之外,在它前面……意味着什么。我在指南中的任何地方都没有像在示例回购中那样看到这一点。

computed: {
  ...mapState({
    messages: state => state.messages
  })
}

当您使用 Vuex 构建大型应用程序时,

您必须在一个地方管理您的商店,而不是将它们分开,

例如,您有一家大型商店,商店中有许多州:

const store =
{
    states: 
    {
        todo:
        {
             notes   : { ... },
             username: { ... },
             nickname: { ... }
        },
        checklist:
        {
             list: { ... }
        }
    } 
}

如果你想使用它们,你可以就这样做

computed:
{
    ...mapState(['todo', 'checklist'])
}

所以你不需要

computed:
{
    todo()
    {
        return this.$store.state.todo
    },
    checklist()
    {
        return this.$store.state.checklist
    }
}

然后像这样使用它们:

todo.notes
todo.usernames
checklist.list

正如@Can Rau 所回答的那样,我将尝试更清楚地说明 h3ll 是传播语法 ...mapGettermapState 和 [=16= 中的实际作用] 在 Vuex 中。

首先,当您没有任何本地计算属性时,您可以直接使用 mapState 作为:computed: mapState 而无需 Spread 语法 ...

mapGettersmapActions


computed: mapState({
    count: state => state.count,
    },

computed: {
  ...mapState({
     count: state => state.count,
  })
}

以上两者做的完全一样!

但是当你有任何本地计算 属性 时,你就需要 Spread Syntax。

这是因为mapState returns一个对象。 然后我们需要 Object Spread Operator 将多个 Object 合并为一个。

computed: {
  localComputed () { /* ... */ },
  // mix this into the outer object with the object spread operator
  ...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 对此解释得很清楚。再深入一点,你就会明白了。