我对 mapstate 的作用不太了解,除此之外,还有什么......在它面前意味着什么。我在指南中没有像示例存储库中那样多地看到这一点。
computed: {
...mapState({
messages: state => state.messages
})
}
Run Code Online (Sandbox Code Playgroud)
Yam*_*mel 12
当您使用 Vuex 构建大型应用程序时,
您将不得不在一个地方管理您的商店,而不是将它们分开,
例如,您有一家大型商店,并且商店中有许多州:
const store =
{
states:
{
todo:
{
notes : { ... },
username: { ... },
nickname: { ... }
},
checklist:
{
list: { ... }
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用它们,你可以这样做
computed:
{
...mapState(['todo', 'checklist'])
}
Run Code Online (Sandbox Code Playgroud)
所以你不要有
computed:
{
todo()
{
return this.$store.state.todo
},
checklist()
{
return this.$store.state.checklist
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它们:
todo.notes
todo.usernames
checklist.list
Run Code Online (Sandbox Code Playgroud)
正如@Can Rau 所回答的那样,我将尝试更清楚地了解 h3ll 是 Spread Syntax在和Vuex 中...实际执行的操作。mapGettermapStatemapActions
首先,当您没有任何本地计算属性时,您可以直接使用mapStateas:computed: mapState而不使用扩展语法。...
mapGetters与和相同mapActions
computed: mapState({
count: state => state.count,
},
computed: {
...mapState({
count: state => state.count,
})
}
Run Code Online (Sandbox Code Playgroud)
上面两个做的事情完全一样!
但是,当您确实有任何本地计算属性时,您就需要扩展语法。
这是因为mapState返回一个对象。然后我们需要对象扩展运算符将多个对象合并为一个。
computed: {
localComputed () { /* ... */ },
// mix this into the outer object with the object spread operator
...mapState({
// ...
})
}
Run Code Online (Sandbox Code Playgroud)
您可以在MDN中阅读有关对象字面量中的 Spread的更多信息
基本上,在这种情况下,它用于合并对象
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
Run Code Online (Sandbox Code Playgroud)
Vuex 文档对此解释得非常清楚。更深入地观察一下,你就会明白了。
| 归档时间: |
|
| 查看次数: |
1988 次 |
| 最近记录: |