GaryO
GaryO

Reputation: 6338

How to use MutationAction in vuex-module-decorators?

I'm trying to use vuex-module-decorators from https://championswimmer.in/vuex-module-decorators. Let's say my module's state has a prop dir that's a dict: {[key: string]: string} Can I use @MutationAction to update an element of that dict? The code below isn't right but hopefully gets across what I mean.

export default class Module extends VuexModule {
  dir: {[key: string]: string}

  @MutationAction(???)
  updateDir(keyValue) {
    return keyValue // ???
  }
}

Is there some doc on how to use @MutationAction, what args it takes and what actual mutation it commits?

Upvotes: 4

Views: 6195

Answers (2)

Arnav Gupta
Arnav Gupta

Reputation: 976

Here is what you should be doing -

export default class Module extends VuexModule {
  dir: {[key: string]: string}

  @MutationAction(['dir'])
  async updateDir(keyValue) {
    const currDir = this.dir

    // do any async work (network req) here
    currDir['myKey'] = keyValue

    return ( { dir: currDir } )
  }
}

But if you really did not need to any async work in the first place.

export default class Module extends VuexModule {
  dir: {[key: string]: string}

  @Mutation
  async updateDir(keyValue) {
    this.dir.myKey = keyValue
  }
}

P.S. I am the author of vuex-module-decorators

Upvotes: 8

Francesco Cina
Francesco Cina

Reputation: 947

I am a newbie with vuex, anyway, this compiles:

export class MyModule extends VuexModule {

    public dir: { [key: string]: string } = {};

    @MutationAction({ mutate: ['dir'] })
    public async updateDir(key: string, value: string) {
        const newDir: { [key: string]: string } = {};
        newDir[key] = value;
        return {
            dir: newDir,
        };
    }

    @MutationAction({ mutate: ['dir'] })
    public async addToDir(key: string, value: string) {
        this.dir[key] = value;
        return {
            dir: this.dir,
        };
    }
}

Please note that I don't know if it is acceptable to modify and reassign the 'dir' variable as I do in the second function.

Upvotes: 0

Related Questions