注意看註釋 關鍵屬性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快捷方法接受的類型挺多要注意