【问题标题】:Three periods syntax in Vuex?Vuex 中的三个句点语法?
【发布时间】:2016-10-04 14:29:55
【问题描述】:

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

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

【问题讨论】:

    标签: vuex


    【解决方案1】:

    当您使用 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
    

    【讨论】:

    • 我要补充一点,你实际上可以只做computed: mapState(['todo']),但是你不能有本地计算属性,通过使用三个点(扩展运算符)(包裹在花括号中,你包括所有的道具mapState 在您的对象中,然后可以定义其他本地属性..所以它合并两个对象有点像Object.assign()
    • @CanRau 您应该将您的评论放入答案中!我花了一天的时间试图弄清楚为什么我们需要在 mapGetters 或 mapState 等中使用 Spread Synxtax。在 Vuex 文档中,示例非常简短且不清楚。当我们没有任何本地计算属性时,我不知道我们可以像computed: mapState([ ])computed: getters([ ]) 那样直接使用它
    • ? 好点子,感谢您花时间做这件事,这样人们可以更快地找到它?
    【解决方案2】:

    正如@Can Rau 所回答的那样,我将尝试更清楚地说明 h3ll 是传播语法 ... 在 Vuex 中的 mapGettermapStatemapActions 中实际执行的操作。

    首先,当您没有任何本地计算属性时,您可以直接将mapState 用作:computed: mapState 而不使用扩展语法...

    mapGettersmapActions 也一样

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

    以上两者的作用完全相同!

    但是当你确实有任何本地计算属性时,你需要传播语法。

    这是因为 mapState 返回一个对象。 然后我们需要 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 非常清楚地解释了这一点。深入了解一下,你就会明白了。

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 2016-07-10
      • 2019-12-03
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多