>[success] state是Vuex中所有數據存儲的地方
## 一:在組件中獲取`state`
由于 Vuex 的狀態存儲是響應式的,從 store 實例中讀取狀態最簡單的方法就是在[計算屬性](https://cn.vuejs.org/guide/computed.html)中返回某個狀態:
~~~
// 創建一個 Counter 組件
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
~~~
## 二: `mapState`輔助函數
當一個組件擁有**多個狀態**的時候,這些狀態都聲明為計算屬性會有些重復和冗余,為了解決這個問題,我們可以使用`mapState`輔助函數幫助我們生成計算屬性
~~~
// 在單獨構建的版本中輔助函數為 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭頭函數可使代碼更簡練
count: state => state.count,
// 傳字符串參數 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態,必須使用常規函數
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
~~~
當映射的計算屬性的名稱與 state 的子節點名稱相同時,我們也可以給`mapState`傳一個字符串數組。
~~~
computed: mapState([
// 映射 this.count 為 store.state.count
'count'
])
~~~
## 三:對象展開運算符
`mapState`函數返回的是一個對象。我們如何將它與局部計算屬性混合使用呢?通常,我們需要使用一個工具函數將多個對象合并為一個,以使我們可以將最終對象傳給`computed`屬性。但是自從有了[對象展開運算符](https://github.com/sebmarkbage/ecmascript-rest-spread),我們可以極大地簡化寫法:
~~~
computed: {
localComputed () { /* ... */ },
// 使用對象展開運算符將此對象混入到外部對象中
...mapState({
// ...
})
}
~~~