vuex-module-decorators
vuex-module-decorators copied to clipboard
Correct way to call a mutation within an action
Hey everyone,
I have a short question, if this is a correct way to trigger a mutation within an action:
export class MyModule extends VuexModule {
myProp: string = '';
@Mutation
private SET_MY_PROP(value: string) {
this.myProp = value;
}
@Action
public async setMyProp(value: string) {
this.SET_MY_PROP(value);
}
}
I am asking, because those get started examples commit the mutation differently like:
@Action({ commit: 'SET_MY_PROP' })
async setMyProp(value: string) {
return value;
}
or like
@Action
async setMyProp(value: string) {
this.context.commit('SET_MY_PROP', value);
}
@souphuhn Personally I use the first example, calling the method instead of annotating. Reasons:
- tooling recognizing that
SET_MY_PROP
is actually used (and therefore not dead code) - code-completion works
- intuitive for newcomers to your project (it's just calling a class method)
One 'danger' I have noticed, is that it's tempting to use more than one argument for the mutation -- your IDE won't mind, but it won't work as expected.
// This won't work
export class MyModule extends VuexModule {
myProp: string = '';
@Mutation
private SET_MY_PROP(value1: string, value2: string) {
this.myProp = value1 + value2;
}
@Action
public async setMyProp(value: string) {
this.SET_MY_PROP('hello', value);
}
}
// This will
export class MyModule extends VuexModule {
myProp: string = '';
@Mutation
private SET_MY_PROP([value1, value2]: [string, string]) {
this.myProp = value1 + value2;
}
@Action
public async setMyProp(value: string) {
this.SET_MY_PROP(['hello', value]);
}
}
I also ask myself the same question every time and seems no one could explain why the examples are using the latter approach. Maybe this is a "bug" that works? IMHO, this issue should have more attention from the community because if the former approach is indeed a feature it should be the one present in the doc examples
@championswimmer could you provide some explanation here?
I'd like to know the other way to call commit or disptach instead of calling via this.context
@bdockbockd just call your mutations from your actions like normal method calls