【问题标题】:Can I use "this" in mapMutations spread inside Vue instance methods?我可以在 Vue 实例方法中传播的 mapMutations 中使用“this”吗?
【发布时间】:2019-02-04 16:47:57
【问题描述】:

我想设置 Vuex 突变如下:

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

但我发现了错误:

未捕获的类型错误:无法读取未定义的属性“存储”

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

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

【问题讨论】:

  • ...mapMutations(['changeModel']) 有什么问题?你想映射this.$store.commit('changeModel') - 还是别的什么?
  • 我要映射this.$store.commit('form1/changeModel'),其中form1是从props设置的。
  • @mcmimik 为什么要直接在组件中使用突变而不是操作?
  • @BennettDams 你说得对,应该在这里使用动作。

标签: javascript vue.js this vuex vuex-modules


【解决方案1】:

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() 相比)之外,我不确定这会增加多少,但也许您的要求比示例代码更复杂。

【讨论】:

  • 非常好。如果您有时间,这将是一个很好的文档功能请求,可以添加到他们的问题列表中。
  • the API guide for mapMutations 确实介绍了这一点。
【解决方案2】:

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

methods: {
  changeModel() {
    this.$store.dispatch(`${this.store}/changeModel`);
  }
}

【讨论】:

  • 甚至是this.$store.commit(),这是您将用于突变的内容
【解决方案3】:

您问的解决方案并不准确,但其效果是相同的。由于突变是一个可变参数,因此很明显将其作为输入参数放入函数中,而不是更改突变名称。我会像这样在商店中创建一个动作:

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

我会在将突变名称传递给它的组件中使用此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2018-03-17
    • 1970-01-01
    • 2018-03-12
    • 2010-10-21
    • 1970-01-01
    相关资源
    最近更新 更多