Vue 教程第十七 篇—— Vuex 之 module

module

因爲使用單一狀態樹,應用的全部狀態會集中到一個比較大的對象。當應用變得很是複雜時,store 對象就有可能變得至關臃腫。javascript

爲了解決以上問題,Vuex 容許咱們將 store 分割成模塊(module)。每一個模塊擁有本身的 state、mutation、action、getter。html

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const moduleA = {
    state: {
        countA: 0
    },
    getters: {
        totalA: (state) => (symbol) => {
            return (symbol || '$') + state.countA
        }
    },
    mutations: {
        incrementA(state, payload){
            state.countA += (payload || 1);
        }
    }
}

const moduleB = {
    state: {
        countB: 0
    },
    getters: {
        totalB: (state) => (symbol) => {
            return (symbol || '$') + state.count
        }
    },
    mutations: {
        incrementB(state, payload){
            state.countB += (payload || 1);
        }
    }
}
const store = new Vuex.Store({
    modules: {
        moduleA,
        moduleB
    }
})

export default store

component

<input type="button" value="increment" @click="add()"/>
<span>{{countA}}</span>
<script>
    import {mapState, mapMutations, mapActions} from 'vuex';

    export default {
        methods: {
            ...mapMutations(['incrementA']),
            ...mapMutations({add: 'incrementA'})
        },
        computed: {
            ...mapState({
                countA: state => state.moduleA.countA
            })
        }
    }
</script>

小結

  • 每一個模塊中的 state、mutation、action、getter 都是獨立的做用域
  • 不一樣模塊間的 state、getter 的屬性存在同級同名的狀況下會報錯
  • mutation、action 等方法同名的話會全部模塊一塊兒觸
  • 解決以上問題,須要給每一個模塊再作一層做用域分離——命名空間

命名空間

store.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const moduleA = {
    namespaced: true,
    state: {
        count: 0
    },
    getters: {
        total: (state) => (symbol) => {
            return (symbol || '$') + state.count
        }
    },
    mutations: {
        increment(state, payload){
            state.count += (payload || 1);
        }
    }
}

const moduleB = {
    namespaced: true,
    state: {
        count: 0
    },
    getters: {
        total: (state) => (symbol) => {
            return (symbol || '$') + state.count
        }
    },
    mutations: {
        increment(state, payload){
            state.count += (payload || 1);
        }
    }
}
const store = new Vuex.Store({
    modules: {
        moduleA,
        moduleB
    }
})

export default store

帶命名空間的綁定函數

methods: {
    ...mapMutations(['moduleA/increment']),
    ...mapMutations({add: 'moduleA/increment'})
},
computed: {
    ...mapState({
        countA: state => state.moduleA.count
    })
}
相關文章
相關標籤/搜索