Search code examples
vue.jsecmascript-6vuexes6-class

Is it OK to use ES6 classes for Vuex modules, mutations and actions?


I am going to create reusable Vuex modules this way:

// parent class to keep all the common CRUD actions
class ListModule {
    state: getInitialState(),
    actions: new ListActions(),
    mutations: new ListMutations()
}

...
class FooMutations extends ListMutations {
    // some additional mutations
}

// class with parent's actions and data structure, but modified mutations
class FooModule extends ListModule {
    mutations: new FooMutations()
}

This is how I would like to avoid duplicating CRUD operations and extend them for certain modules if it is necessary.

All modules will be used with namespacing.

Are there any potential problems?


Solution

  • It might be possible but it seems unnecessarily complicated to use classes when you just need objects.

    const listMutations = {
      // mutations here
    }
    
    // 'extend' listMutations
    const fooMutations = {
      ...listMutations,
      // some additional mutations
    }
    
    const listModule = {
      state: getInitialState(),
      actions: listActions,
      mutations: listMutations
    }
    
    // 'extend' listModule
    const fooModule = {
      ...listModule,
      mutations: fooMutations
    }