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.

nuxt.jsのstoreの初期化方法

Last updated at Posted at 2020-07-20

概要

以下のような初期化ではなく、あらかじめ初期値を宣言することで初期化する方法の紹介です

export const state = {
    text: '',
    arr: [],
    obj: {}
}

export mutations = {
    resetState(state) {
        state.text = ''
        state.arr = []
        state.obj = {}
    }
}

コード(例)

// 今回 deep copy するために使用
import { cloneDeep } from 'lodash'

// state の初期値を宣言
const initialState = {
    text: '',
    arr: [],
    obj: {}
}

// 初期値を deep copy 
export const state = () => cloneDeep(initialState)

export const mutations = {
    resetState(state) {
        Object.keys(state).forEach(key => {
            // state のキー毎に initialState で定義した初期値を deep copy して代入
            state[key] = cloneDeep(initialState[key])
        })
    }
}

注意点

  • 最初のstateの宣言、resetStateでの代入はdeep copyで行わなければならない
  • shallow copyで行うとinitialStateの値自体が書き換わってしまい正常に初期化できない場合がある
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?