Search code examples
vuejs2vuexvuex-modules

Vuex: add to prototype so I can do something like object.save()?


All my Vuex modules use base UPSERT, UPDATE, DELETE functions so I would love to not type this.$store.dispatch('UPSERT', object) in my components and instead type object.save(). I assume this is easy, but not sure if there are any issues with doing this or how to do this.

    export interface ITaskMessage {
      id?: string
      message: string | null
      save(): any
    }
    
    export class TaskMessage implements ITaskMessage {
      id?: string
      message: string | null = ''
      save() {
        window._actions['UPSERT']
      }
    }

This code is from types.ts inside a module. I assume I need to import something in this file and then use that inside the class declaration. I'm just not sure what it should be.


Solution

  • It was simpler than I was making it out to be. Basically, import the store into the file:

    import store from '@/store'
    

    Then, fill in the save method:

      public save() {
        store.dispatch('UPSERT', this)
      }