Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex unregisterModule what does it do?

I'm a bit confused with what unregisterModule is actually doing.

If we have a module like so:

{
    state: {
        page: 1
    }
}

Then un/register it dynamically:

beforeCreate() {        
    this.$store.registerModule('items', store);
},

beforeDestroy() {
    this.$store.unregisterModule('items');
},

If we make a change to page navigate a way (which triggers unregister) then navigate back.

It seems the state persists? I would think unregister completely kills the module and all data, states, etc?

I can make the state a function like so:

{
    state() {
        return {
            page: 1
        }
    }
}

But, then it still doesn't change the question then of what does unregisterModule actually do then?

Also does it mean I would either have to change all my state objects into functions or have some kind of reset method on unregister. This seems quite pointless, what am I missing here?

like image 283
Rob Avatar asked Jul 04 '19 09:07

Rob


1 Answers

unregisterModule removes the module and you cannot access it.

The state doesn't persists but you have to use the state as a function

From docs:

If we use a plain object to declare the state of the module, then that state object will be shared by reference and cause cross store/module state pollution when it's mutated.

This is actually the exact same problem with data inside Vue components. So the solution is also the same - use a function for declaring module state.

See it live on codesandbox:

  • In Home page (the module registers), increase the counter
  • In About page (the module is unregistered)
  • In Contact page we re-register the module.
  • Observe that the counter is NOT persisted.
like image 196
Roland Avatar answered Oct 12 '22 13:10

Roland