2.4 Vuex最佳实践

一、核心概念补充

  1. State:this.$store.state.xxx,mapState 取值

  2. Getter:this.$store.getters.xxx,mapGetters 取值

  3. Mutation:this.$store.commit("xxx"),mapMutations 赋值

  4. Action:this.$store.dispatch("xxx"),mupActions 赋值

  5. Module

二、使用常量代替Mutation事件类型

// mutation-types.js
export const SOME_MUTATION = 'SOME_MUTATION'

// stors.js
import Vuex from 'vuex'
import {SOME_MUTATION} from './mutation-types'

const store = new Vuex.Store({
    state: {...},
    mutations: {
        [SOME_MUTATION] (state) {
            // mutate state
        }
    }
})

三、Module(命名空间)

  1. 开启命名空间 namespaced:true

  2. 嵌套模块不要过深,尽量扁平化

  3. 灵活应用 createNamespacedHelpers

Last updated