我可以在 Vue 实例方法内部传播的 mapMutations 中使用 "this" 吗?

Can I use "this" in mapMutations spread inside Vue instance methods?

我想按如下方式设置 Vuex 突变:

export default {
    props: {
        store: String
    },
    methods: {
        ...mapMutations({
            changeModel: `${this.store}/changeModel`
        })
    }
}

但我发现错误:

Uncaught TypeError: Cannot read property 'store' of undefined

如何在模块突变名称中正确使用 props

我想映射 this.$store.commit('form1/changeModel'),其中 form1 是根据 props 设置的。

我认为没有办法在 mapActions 上绑定它。但是你可以用 $store.dispatch

来调用它
methods: {
  changeModel() {
    this.$store.dispatch(`${this.store}/changeModel`);
  }
}

Vuex 助手 mapMutations 可以与 this 一起使用的函数一起使用。

似乎没有这方面的文档,但 Vuex 单元测试 helpers.spec.js 说明了该模式。

const vm = new Vue({
  store,
  methods: mapMutations({
    plus (commit, amount) {
      commit('inc', amount + 1)
    }
  })
})

作为奖励,该函数允许将参数传递给突变,这是一个常见的要求。

您的代码更改为:

export default {
  props: {
    store: String
  },
  methods: {
    ...mapMutations({
      changeModel(commit) { commit(`${this.store}/changeModel`) }
    })
  }
}

组件内的调用只是 changeModel() - mapMutations 负责注入 commit 参数。

请注意,除了一些额外的噪音(与简单的 this.$store.commit() 相比)之外,我不确定这会增加多少,但也许您的要求比示例代码更复杂。

你问的解决方案不完全正确,但效果是一样的。由于突变是一个可变参数,显然将其作为输入参数放入函数中而不是更改突变名称。我会像这样在商店中创建一个动作:

changeModel ({dispatch, commit, rootGetters}, mutationName) {
 commit(`${mutationName}/changeModel`, {}, {root: true})
})

我会在将 mutationName 传递给它的组件中使用此操作。