Search code examples
vuejs2vuexvuex-modules

How to empty a Vuex store module state object?


How to empty a Vuex store module state object completely? I know how to delete a single property of state object for e.g Vue.delete(state.slidesList, 'slide1') but I want to completely empty the state object (not delete the object itself) without losing reactivity on the object itself, when individual properties are deleted (using Vue.delete) removes reactive getters and setters, I believe, pls correct if this is wrong.

Does directly setting state.slideList = {} empties the object, while still being reactive? if yes then it implies state.slideList = {fname: 'Appu' } is a way to overwrite the object without emptying the object (if the goal is to overwrite the object completely with another object, rather than empty and re-write in it).

If not, what is the correct way to overwrite the state object with another new non-empty object.

Thanks


Solution

  • set adds a property to a reactive object, ensuring the new property is also reactive, so triggers view updates. This must be used to add new properties to reactive objects, as Vue cannot detect normal property additions. doc

    module.js

    import Vue from 'vue'
    
    const initialState = {
     foo: {},
     bar: {},
     // ...
    }
    
    const state = {...initialState}
    
    const mutations = { // To reset a state
     RESET_FOO (state) {
      Vue.set(state, 'foo', initialState.foo)
     },
    
     UPDATE_FOO (state, payload) { // To update the state
      Vue.set(state, 'foo', payload)
     },
    
     UPDATE_IN_FOO (state, { key, value }) { // To update a key in a state
      Vue.set(state.foo, key, value)
     },
    
     RESET_MODULE (state) { // To reset the entire module
      Object.assign(state, initialState)
     }
    }