[Vuex] state全て破棄する方法

1 min read
hiroweb developer

ログアウト処理などで state をすべて破棄したい。

Vuex に組み込みでdestoryState(),clearState()的な API が生えているのを期待していたのだが、無いようなので泥臭く実装を行う。

方法

以下のような実装を行う。

const initialState = {
  token: "",
  isAuthenticated: false,
};

export const state = () => Object.assign({}, initialState);

export const mutations = {
  destroySession(state) {
    for (let key in state) {
      if (initialState.hasOwnProperty(key)) {
        state[key] = initialState[key];
      }
    }
  },
};

簡単にいえば、対象の state をループで削除していく処理である。

  1. stateinitialStateと別で定義
  2. mutations のdestroySession()内で初期化
  3. stateinitialStateで key が一致しているものだけinitialStateで初期化する