LoginSignup
0
0

More than 1 year has passed since last update.

Nuxt.jsのstoreで他のモジュールのstateやmutationsを使用する方法

Last updated at Posted at 2022-01-13

はじめに

Nuxt.js storeをモジュールで使用するときに別のモジュールのmutationsやらstateを利用したくなって調べたのでメモを残します。

目次

  1. AモジュールでBモジュールの値を参照する(state)
  2. Aモジュールから別モジュールのMutationsを使用
  3. 参考文献

AモジュールでBモジュールの値を参照する(state)

別のモジュールのstateを参照するパターン

rootStateを使用

// AモジュールからBモジュールを参照
export const actions = {
  add ({ rootState }, hoge) {
    const bMosule = rootState.b.bState
    this.$axios.$patch(url+ 'post/' + selectedBook.id, {
      post: {
        // 送る値
      }
    })
      .then((response) => { // レスポンス

addにrootStateでrootを読み込ませてroot経由でBモジュールの値を参照します。
直接Bモジュールを読み込むことはできないが、rootを経由すると参照可能になる。

× A → B.state

○ A → root → B.state

Aモジュールから別モジュールのMutationsを使用

別モジュールのMutationsを使用

commitの第3引数に {root: true} を使用

① rootのMutationsを使用

// index.jsのalertを使える
commit('alert', true, { root: true })

第2引数にはいつも通り渡したい値をセットします。
今回の場合はrootのMutationsであるalertを使用しています。

② BモジュールのMutationsを使用

// BモジュールのbAlertMutationsを使える
commit('B/bAlert', true, { root: true })

root経由でBモジュールのMutationsを使用できます。

参考文献

0
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
0
0