championswimmer / vuex-module-decorators

TypeScript/ES7 Decorators to create Vuex modules declaratively
https://championswimmer.in/vuex-module-decorators/
MIT License
1.8k stars 170 forks source link

Access to getter inside mutation #271

Open Glandos opened 4 years ago

Glandos commented 4 years ago

Hi, I have the following pattern:

import { VuexModule, Module, Mutation } from 'vuex-module-decorators'
import { Investigation, InvestigationId } from './types'

@Module({ name: 'investigations' })
class Investigations extends VuexModule {
  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
  newSequence ({ investigationId }: { investigationId: InvestigationId }): number {
    const investigation = this.id(investigationId)
    if (investigation === undefined) {
      throw Error(`Investigation not found: ${investigationId}`)
    }
    return investigation.sequences.push({})
  }
}

However, when accessing to newSequence, it seems that this.id is undefined. This is not consistent with the behavior with getters nor actions (where it's possible to use context).

Am I missing something?

weilbith commented 4 years ago

I does also not work between getters, doesn't it?

Glandos commented 4 years ago

As far as I remember yes. However, since it was for a new project, I then switched to another helper library (vuex-class-component)

weilbith commented 4 years ago

Yeah, apparently you can't access anything from the class inside getters or other functions (except the "state"). Okay, I'll checkout your option. :+1:

weilbith commented 4 years ago

I'll also look into Vue3 and Vuex4. Let's see.

davemecha commented 3 years ago

It would so great to have a solution for this.

Glandos commented 3 years ago

In fact, I encountered the exact same issue with vuex-class-component, except that I can use a workaround (with proxies).

See my comment on this: it seems that Vuex itself renders this usage quite complicated.

firstsmarts commented 3 years ago

Any progress about this?