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

标签 javascript vue.js this vuex vuex-modules

我想按如下方式设置 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 设置的。

最佳答案

Vuex helper 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 负责注入(inject) commit 参数。

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

关于javascript - 我可以在 Vue 实例方法内部传播的 mapMutations 中使用 "this"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52085190/

相关文章:

javascript - 使用 jQuery 显示嵌套的 UL

javascript - 如何在不重新绑定(bind) this 的情况下返回带有粗箭头函数的对象?

javascript - 如何保存WebView应用程序的登录信息?

javascript - 对象列表 : return object with highest attribute value

vue.js - 如何将参数从 vue 自定义元素传递到 vue 组件?

css - 在 Vue 应用程序的构建阶段定义 css pack

Javascript 安全 : is storing sensitive data in a self invoking function more secure than cookies?

javascript - JQuery .click 不像我期望的那样工作。为什么?

unit-testing - 如何在 JEST 测试中模拟全局 Vue.js 变量

javascript - typescript 错误? `this` `get` 语法和 `defineProperty` 的 `get` 之间的差异