vuex入門

vuex 的建立和基本屬性和觸發發方法

注意看註釋 關鍵屬性 modules state getters mutations actions
const store = new Vuex.Store({
    modules: { 
        someModaule1: {  //  模塊1
            namespaced: true,
            state: {  // 狀態
                count: 0
            },
            getters: {  // getters,會緩存屬性
                getCount: (state, getters) => {
                    return state.someMOdaule1.count + getters.length
                }
            },
            actions: {   // 動做 ,支持異步,結果仍是要觸發 Mutation,  經過 store.dispatch('someModaule1/increment')觸發
                increment (context,arg) {
                    console.log(arg)
                    context.commit('increment')
                } 
            },
            mutations: { // Mutation必須爲同步函數,去改變state, store.commit('someMOdaule1/increment', 10)
                increment (state, n) {
                    state.count += n
                }
            },

            modules: {  // 嵌套模塊
                someModaule1: {  // 繼承父模塊的命名空間
                    state: { ... },
                    getters: {
                        profile () { ... } // -> getters['someModaule1/someModaule1']
                    }
                },
            }
        },
        someModauleOther: {...} // 其餘模塊
    }
})

調用vue

store.dispatch('someModaule1/increment')  // 觸發action
store.commit('someMOdaule1/increment', 10)   // 觸發mutations

在組件中使用

大型項目一般用以下方法 mapState() mapGetters() mapActions() mapMutations()
Vue.use(Vuex)

const Counter = {
    template: `<div>{{ count }}</div>`,
    store:store, // 把 store 對象提供給 「store」 選項,這能夠把 store 的實例注入全部的子組件
    computed: {
        computed: {
            ...mapState('someModaule1', {
                'count',  // 傳字符串參數 'count' 等同於 `state => state.count`  映射 this.count 爲 store.someModaule1.state.count
            }),
            ...mapGetters('someModaule1',[
                'getCount',
            ])
        },
    },
    methods: {
        ...mapActions('someModaule1',[
            'increment', // 將 `this.increment()` 映射爲 `this.$store.dispatch('someModaule1/increment')`
        ]),
        ...mapMutations([
            'increment', // 將 `this.increment()` 映射爲 `this.$store.commit('increment')`
        ])
    }
}
mapState和其餘map快捷方法接受的類型挺多要注意
  • {} 從新命名相應的屬性和方法,若是不重命名建議用下面的數組簡寫
  • [string] 字符串簡寫,見上面註釋
  • string,[string] 加命名空間的,字符串簡寫
相關文章
相關標籤/搜索