首页 > 解决方案 > 如何在 vuex-module-decorators 中使用 MutationAction?

问题描述

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

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

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

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

标签: typescriptvuex

解决方案


这是你应该做的 -

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 } )
  }
}

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

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

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

PS我是作者vuex-module-decorators


推荐阅读