1

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

3 Answers 3

3

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) } } 
Sign up to request clarification or add additional context in comments.

2 Comments

@appu please let me know if I missed any relevant case, above, that may be required in your use case. Thanks
Object.assign() copies/overwrites the state properties with/from the ones from initialState. If you miss to declare a property in initialState, it will not get reset in the state and remains like before. Be careful about this.
1

Vuex has replaceState method that replaces store's root state.

1 Comment

Please could you show this with an example?
0

Create a mutation that resets the state. Then, reset the state with a default value like this:

Object.assign(state, newState) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.