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?

More than 3 years have passed since last update.

Vuexのstateをシンプルに初期化したい

Posted at

はじめに

大量に宣言されたstateを初期化する必要があり、全部変数に値を入れ直すなんてい・や・だ、と思って、いろいろ試しましたがこんな形に落ち着きました。ご参考まで。

実装内容

store/index.js
const initialState = {
  // 通常stateに記載する値を記載
  user: null
}

export const state = () => Object.assign({}, JSON.parse(JSON.stringify(initialState)))

export const getters = {
  user: (state) => state.user,
}

export const mutations = {
  INIT_DATA(state) {
    Object.assign(state, JSON.parse(JSON.stringify(initialState)))
  }
}

export const actions = {
  initData({ commit }) {
    commit('INIT_DATA')
  }
}
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?