如何在 vuex-module-decorators 中使用 MutationAction?

Gar*_*ryO 4 typescript vuex

我正在尝试使用来自https://championsswimmer.in/vuex-module-decorators 的vuex-module-decorators 。假设我的模块的 state 有一个dirdict的 prop :{[key: string]: string}我可以@MutationAction用来更新该 dict 的元素吗?下面的代码不正确,但希望能理解我的意思。

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

  @MutationAction(???)
  updateDir(keyValue) {
    return keyValue // ???
  }
}
Run Code Online (Sandbox Code Playgroud)

是否有一些关于如何使用的文档@MutationAction,它需要什么参数以及它提交的实际突变?

Arn*_*pta 8

这是你应该做的 -

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 } )
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您一开始就真的不需要任何异步工作。

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

  @Mutation
  async updateDir(keyValue) {
    this.dir.myKey = keyValue
  }
}
Run Code Online (Sandbox Code Playgroud)

PS我是作者 vuex-module-decorators

  • 谢谢——如果文档有一个关于如何使用“@MutationAction”的更详细的部分那就太好了——它的内部功能、返回什么、更新还是替换、如何处理错误。 (2认同)