Vuex使用單一狀態(tài)樹,用一個對象就包含了全部的應用層級狀態(tài),那么如何獲取狀態(tài)呢场勤,最簡單的方法就是在“計算屬性”中返回某個狀態(tài)
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return store.state.count
}
}
}
每當store.state.count變化時,都會重新請求計算屬性歼跟,并且出發(fā)相關dom更新和媳。
下面是子組件中的用法,在根實例中注冊store
Vue.use(Vuex)
new Vue({
store
})
下面在每個子組件中哈街,使用this.$store.state.count就可以訪問到
const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count () {
return this.$store.state.count
}
}
}
是不是很簡單
mapState 輔助函數(shù)
當你的一個組件需要獲取多個狀態(tài)時留瞳,一個一個聲明計算屬性會有些重復和冗余,使用mapState骚秦,就會幫助我們自動生成她倘,節(jié)省很多時間
import { mapState } from 'vuex'
export default {
computed: mapState({
// 箭頭函數(shù)可使代碼更簡練
count: state => state.count,
// 傳字符串參數(shù) 'count' 等同于 `state => state.count`
countAlias: 'count',
// 為了能夠使用 `this` 獲取局部狀態(tài),必須使用常規(guī)函數(shù)
countPlusLocalState (state) {
return state.count + this.localCount
}
})
}
//當計算屬性名稱和state子節(jié)點名稱相同時骤竹,我們可以傳一個字符串數(shù)組
computed: mapState([
'count1','count2'
])
//一般computed里還有其他計算屬性帝牡,這是我們要混合使用的話,可以使用對象展開運算符
computed: {
localComputed () {....},
...mapState({ //或者這里改為數(shù)組
countAlias: 'count'
})
}
以上就是Vuex中 state數(shù)據(jù)的讀取方法蒙揣,通過this.store.state[key]獲取我們想要的參數(shù)靶溜,同時在computed里返回就可以得到啦,同時還有一個mapState供我們在需要獲取很多數(shù)據(jù)的時候使用懒震,下一節(jié)罩息,我們將介紹getter的用法~
引用
https://vuex.vuejs.org Vuex官方文檔