0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vuexでstoreをモジュール分けする

Posted at

Vuexのstoreにモジュール分けする

参考:https://qiita.com/youstr/items/a3a484b6669e67928e42
モジュール分けする前は以下の様にしてidTokenを保存していました。

store/index.js
import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'

export default createStore({
    state: {
        idToken: null,
    },
    mutations: {
        SET_IDTOKEN(state, idToken) {
            state.idToken = idToken
        },
        LOGOUT(state) {
            state.idToken = null
        },
    },
    plugins: [
        createPersistedState({
            key: 'key',
            paths: ['idToken'],
            storage: window.sessionStorage,
        }),
    ],
})

現状だとidTokenしか保存していませんが、今後保存する値が増えると、たくさん書かなければならなくなるのでモジュール分けしたいと思います。

store/index.jsではauthモジュールを呼び出すだけにします。

store/index.js
import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'

// モジュールをインポート
import auth from './modules/auth'

export default createStore({
    modules: {
        auth,
    },
    plugins: [
        createPersistedState({
            key: 'key',
            paths: ['auth'],
            storage: window.localStorage,
        }),
    ],
})

store/modules/auth.jsでは認証情報の処理を書きます。

store/modules/auth.js
const state = {
    idToken: null,
    accessToken: null,
    refreshToken: null,
}

const mutations = {
    SET_TOKENS(state, tokens) {
        state.idToken = tokens.idToken
        state.accessToken = tokens.accessToken
        state.refreshToken = tokens.refreshToken
    },
    LOGOUT(state) {
        console.log('state', state)
        state.idToken = null
        state.accessToken = null
        state.refreshToken = null
    },
}

const actions = {
    setTokens({ commit }, tokens) {
        commit('SET_TOKENS', tokens)
    },
    logout({ commit }) {
        commit('LOGOUT')
    },
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
}

storeに保存した変数はstore.state.auth.idTokenの様にして呼び出せます。
変更前はstore.state.idTokenでしたが、モジュール分けすることでモジュール名をstore.state.{モジュール名}にする必要があります。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?