vuex 使用文档小结篇

2020-06-16 05:41:34易采站长站整理

 const moduleA = {
          state: {count:0},
          mutations: {
            increment (state) {
                // state 模块的局部状态
                state.count++
            }
          },
      getters: {
        doubleCount (state) {
        return state.count * 2
        }
      }
    }

   同样对于模块内部的action, context.state 是局部状态,根节点的窗台石context.rootState:    


const moduleA = {
          actions: {
          incrementIfOddOnRootSum ({state, commit ,rootState}) {
            if((state.count + rootState.count) %2 ===1){
                commit('increment')
          }
         }
        }
      }

 对于模块内部的getter,跟节点状态会作为第三个参数:     


const moduleA = {
          getters: {
            getters: {
              sumWithRootCount (state,getters,rootState) {
                      return state.count + rootState.count
                }
              }
          }
        }

命名空间

    模块内部的action, mutation , 和 getter 现在仍然注册在全局命名空间    这样保证了多个模块能够响应同一 mutation 或 action. 也可以通过添加前缀 或者 后缀的

      方式隔离各个模块,以免冲突。     


// 定义 getter, action , 和 mutation 的名称为常量,以模块名 ‘todo' 为前缀。
        export const DONE_COUNT = 'todos/DONE_COUNT'
        export const FETCH_ALL = 'todos/FETCH_ALL'
        export const TOGGLE_DONE = 'todos/TOGGLE_DONE'
         import * as types form '../types'
    // 使用添加了解前缀的名称定义, getter, action 和 mutation
    const todosModule = {
        state : {todo: []},
        getters: {
          [type.DONE_COUNT] (state) {
          }
      }
    actions: {