Vuex之state

wade3po發表於2019-02-02

我們已經把vuex的結構給建起來了,那麼我們怎麼在各個元件中使用vuex的狀態呢?那就是通過state。

我們都知道state是vuex的資料中心,那麼我們頁面可以直接使用,不管是標籤還是js裡面都可以這樣使用:

this.$store.state.test

然後官網推薦從 store 例項中讀取狀態最簡單的方法就是在計算屬性中返回某個狀態:

computed: { test () { return this.$store.state.test }}

然後就可以直接使用this.test了。

如果資料有點多,這樣的計算屬性書寫會有點冗餘,vuex提供了mapState輔助函式生成計算屬性。

陣列:

computed: mapState(['test','mapState'])

物件:

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

跟本地計算屬性混合使用;

computed: {
        localComputed(){
            return '這是區域性計算屬性'
        },
        ...mapState(['test', 'mapState']),
        ...mapState(
            {
                test1: state = > state.test + 'test1',
                mapState1:state =>state.mapState + 'mapState1'
            } 
        )
    }
複製程式碼

上面的幾個方法不管是在標籤還是js裡面都可以直接通過this.呼叫相對應的資料。

還有一個最簡單,但是不推薦使用的方法,直接賦值修改:

this.$store.state.test = '直接修改'

歡迎關注Coding個人筆記 公眾號

相關文章