michaelolof / vuex-class-component

A Type Safe Vuex Module or Store Using ES6 Classes and ES7 Decorators written in TypeScript.
217 stars 21 forks source link

Calling getter in mutation #75

Open Glandos opened 4 years ago

Glandos commented 4 years ago

I am trying to call a getter with a mutation, and it seems not to work:

import { createModule, createProxy, mutation, action } from 'vuex-class-component'

import { Investigation, InvestigationId, InvestigationsState } from './types'

const VuexModule = createModule({
  namespaced: 'investigations'
})

export class Investigations extends VuexModule implements InvestigationsState {
  investigations: Investigation[] = []
  currentInvestigationIndex = -1

  get current (): Investigation | undefined {
    return this.currentInvestigationIndex >= 0 ? this.investigations[this.currentInvestigationIndex] : undefined
  }

  get id () {
    return (id: InvestigationId): Investigation | undefined => this.investigations.find(i => i.id === id)
  }

  @mutation
  changeSomething ({ investigationId, thing }: { investigationId: InvestigationId, thing: string }): void {
    // ERROR: this.id is not a function
    const investigation = investigationId ? this.id(investigationId) : this.current
    // Do stuff
  }
}

I can work around this by using a proxy within the mutation:

const me = createProxy(this.$store, Investigations)
const investigation = investigationId ? me.id(investigationId) : me.current

But I thought that this could have been done at a higher level. Am I missing something?

Glandos commented 3 years ago

After so many research, my findings are not good news.

It seems that registerMutation from Vuex doesn't provide access to local getters and mutations, as it does with actions and getters. So it's quite impossible to create the local proxy for this.

I am about to create a static member that return the proxy in each VuexModule class…