interfaceStoreType { mm: MyModule } // Declare empty store first const store = newVuex.Store<StoreType>({})
// Create module later in your code (it will register itself automatically) // In the decorator we pass the store object into which module is injected // NOTE: When you set dynamic true, make sure you give module a name @Module({ dynamic: true, store: store, name: 'mm' }) classMyModuleextendsVuexModule { count = 0
// src/module/index.ts function registerDynamicModule<S>(module: Mod<S, any>, modOpt: DynamicModuleOptions) { if (!modOpt.name) { thrownewError('Name of module not provided in decorator options') }
if (!modOpt.store) { thrownewError('Store not provided in decorator options when using dynamic option') }
modOpt.store.registerModule( modOpt.name, // TODO: Handle nested modules too in future module, { preserveState: modOpt.preserveState || false } ) }
function registerDynamicModule<S>(dynamicModule: Mod<S, any>, modOpt: DynamicModuleOptions) { if (!modOpt.name) { thrownewError('Name of module not provided in decorator options') }
if (!modOpt.store) { thrownewError('Store not provided in decorator options when using dynamic option') } if (import.meta.hot) { // 必需的条件守卫, 这样代码就可以在生产环境中被 tree-shaking 优化 // vite 的热更新 if (modOpt.store.hasModule(modOpt.name)) { // 如果遇到重复模块则热更新 modOpt.store.hotUpdate({ modules: { [modOpt.name]: dynamicModule } }) return } modOpt.store.registerModule(modOpt.name, dynamicModule, { preserveState: modOpt.preserveState || false }) return } modOpt.store.registerModule(modOpt.name, dynamicModule, { preserveState: modOpt.preserveState || false }) }
function registerDynamicModule<S>(dynamicModule: Mod<S, any>, modOpt: DynamicModuleOptions) { if (!modOpt.name) { thrownewError('Name of module not provided in decorator options') }
if (!modOpt.store) { thrownewError('Store not provided in decorator options when using dynamic option') } if (module.hot) { // 此处改为 module.hot 来支持 webpack 热更新。 if (modOpt.store.hasModule(modOpt.name)) { // 如果遇到重复模块则热更新 modOpt.store.hotUpdate({ modules: { [modOpt.name]: dynamicModule } }) return } modOpt.store.registerModule(modOpt.name, dynamicModule, { preserveState: modOpt.preserveState || false }) return } modOpt.store.registerModule(modOpt.name, dynamicModule, { preserveState: modOpt.preserveState || false }) }