Skip to content

rootDispatch

javascript
context.dispatch(tpye, payload, { root: true })
context.commit(tpye, payload, { root: true })
javascript
const local = {
  dispatch: noNamespace ? store.dispatch : (type, payload, options) => {

    // 如果未设置 { root: true } 才拼接上 namespace
    // context.dispatch(foo, bar, { root: true }) 代表分发根模块的 foo
    // context.commit(foo, bar, { root: true }) 代表提交根模块的 foo
    if (!options || !options.root) {
      type = namespace + type
      if (__DEV__ && !store._actions[type]) {
        return
      }
    }

    return store.dispatch(type, payload)
  }
}
javascript
new Vuex.Store({
  namespaced: true,
  modules: {
    foo: {
      namespaced: true,
      actions: {
        bar: { // this._actions.bar
          root: true,
          handler () {
            // ...
          }
        },
        baz () { // this._actions.foo/baz
          // ...
        }
      }
    }
  }
})

module.forEachAction((action, key) => {
  // 如果设置了根的 action,初始化时就挂载到根模块上。
  // 并没有提供设置根的 mutation
  const type = action.root ? key : namespace + key
  const handler = action.handler || action
  registerAction(store, type, handler, local)
})