Vuex unregisterModule 有什么作用?

Vuex unregisterModule what does it do?

我对 unregisterModule 实际做的事情有点困惑。

如果我们有这样的模块:

{
    state: {
        page: 1
    }
}

然后un/register它动态地:

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

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

如果我们更改 page 导航方式(触发 unregister)然后导航回来。

状态似乎持续存在?我认为 unregister 完全杀死模块和所有数据、状态等?

我可以像这样使状态成为一个函数:

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

但是,它仍然没有改变 unregisterModule 实际上做了什么的问题?

这是否也意味着我要么必须将所有状态对象更改为函数,要么在注销时使用某种重置方法。这似乎毫无意义,我在这里错过了什么?

unregisterModule 删除模块,您无法访问它。

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

来自文档:

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:

  • 在主页(模块寄存器)中,增加计数器
  • 在关于页面(模块未注册)
  • 在联系页面中,我们 re-register 模块。
  • 观察 计数器未持久化。