How to clear state in vuex store?

后端 未结 12 1294
既然无缘
既然无缘 2020-12-23 12:21

My state in vuex store is huge.

Is there a way to reset all the data in state in one go, instead of manually setting everything to null?

12条回答
  •  天命终不由人
    2020-12-23 13:16

    If you want to reset your entire state you can use the built in replaceState method.

    Given a state set in index.js:

        const state = { user: '', token: '', products: [] /* etc. */ }
        const initialStateCopy = JSON.parse(JSON.stringify(state))
    
        export const store = new Vuex.Store({ state, /* getters, mutations, etc. */ })
    
        export function resetState() {
          store.replaceState(initialStateCopy)
        }
    

    Then in your vue component (or anywhere) import resetState:

        import { resetState } from '@/store/index.js'
    
        // vue component usage, for example: logout
        {
          // ... data(), computed etc. omitted for brevity
          methods: {
            logout() { resetState() }
          }
        }
    

提交回复
热议问题