【发布时间】:2016-10-04 14:29:55
【问题描述】:
我对 mapstate 的作用不是很清楚,除此之外,在它面前……意味着什么。我在指南中没有像示例回购那样看到这一点。
computed: {
...mapState({
messages: state => state.messages
})
}
【问题讨论】:
标签: vuex
我对 mapstate 的作用不是很清楚,除此之外,在它面前……意味着什么。我在指南中没有像示例回购那样看到这一点。
computed: {
...mapState({
messages: state => state.messages
})
}
【问题讨论】:
标签: vuex
当您使用 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()
computed: mapState([ ]) 或computed: getters([ ]) 那样直接使用它
正如@Can Rau 所回答的那样,我将尝试更清楚地说明 h3ll 是传播语法 ... 在 Vuex 中的 mapGetter、mapState 和 mapActions 中实际执行的操作。
首先,当您没有任何本地计算属性时,您可以直接将mapState 用作:computed: mapState 而不使用扩展语法...。
mapGetters 和 mapActions 也一样
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 非常清楚地解释了这一点。深入了解一下,你就会明白了。
【讨论】: