LoginSignup
1
0

More than 3 years have passed since last update.

Vuex_あるモジュールから別モジュールのAction,Mutationを操作する方法

Posted at

Vuexは namespaced: true とすることで、複数のモジュールにファイルを分けて管理することができます。

あるモジュールから別のモジュールのstateを更新したい際、
別のモジュールのAction,Mutationを呼び出す必要があると思います。
(あるモジュールから直接、別モジュールのstateは変更できないように思います。もし間違っていたらすみません。)

コード例

別モジュールのAction,Mutationを呼び出すには、下記のように書きます。

A_module.js
//別モジュールのActionを呼び出す例
 dispatch("B_module/B_module_Action",payload,{root:true});

//別モジュールのMutationを呼び出す例
 context.commit("B_module/B_module_Mutation", payload, {root: true});

第1引数:呼び出したいモジュール名 / (別Action名 or 別Mutation名)
第2引数:呼び出し先に渡す値。
    例:何も渡さない場合はNULL,DBからのレスポンスの場合はresponse.data など。
第3引数:{root:true} ・・・ 別モジュールにアクセスしたい場合、必須の設定。

ポイントは第3引数の{root:true}です。
{root:true}を指定することで、"別モジュール名/別Action名 or 別Mutation名"で呼び出せるようになります。

ちなみに、第3引数を省略した場合は、現在のモジュール内から呼び出そうとします。

終わりに

Vuex公式ガイドのモジュールのページには直接書いていなかったので、記事にしてみました。
公式ガイドの説明を下記のようにしてほしかった・・・

誰かの参考になりましたら幸いです。

Vuex公式ガイド モジュール

A_module.js
//公式ガイドより抜粋

actions: {
        dispatch('someOtherAction') // -> 'foo/someOtherAction'
        dispatch('someOtherAction', null, { root: true }) // -> 'someOtherAction'
        //別モジュールから呼び出す場合
     dispatch('B/someOtherAction', null, { root: true }) // -> 'B/someOtherAction'

        commit('someMutation') // -> 'foo/someMutation'
        commit('someMutation', null, { root: true }) // -> 'someMutation'
       //別モジュールから呼び出す場合
        commit('B/someMutation', null, { root: true }) // -> 'B/someMutation'

    }

参考

【Vue】Vuexで他のモジュールのActionをDispatchする

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0