简体   繁体   English

我可以在Vue实例方法中使用mapMutations中使用“this”吗?

[英]Can I use “this” in mapMutations spread inside Vue instance methods?

I want to set Vuex mutations as follows: 我想将Vuex突变设置如下:

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

But I catch the error: 但我抓住了这个错误:

Uncaught TypeError: Cannot read property 'store' of undefined 未捕获的TypeError:无法读取未定义的属性“store”

How do I correctly use props inside the module mutation name? 如何在模块变异名称中正确使用道具

I want to map this.$store.commit('form1/changeModel') , where form1 is set from props . 我想映射this.$store.commit('form1/changeModel') ,其中form1是从props设置的。

I think there is no way to bind this on mapActions. 我认为没有办法在mapActions上绑定它。 But you can call it with $store.dispatch 但你可以用$store.dispatch调用它

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

Vuex helper mapMutations can be used with a function which works with this . Vuex辅助mapMutations可以与一个适用this的函数一起使用。

There does not seem to be a doc for this, but the Vuex unit test helpers.spec.js illustrates the pattern. 似乎没有这方面的文档,但Vuex单元测试helpers.spec.js说明了模式。

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

As a bonus, the function allows passing a parameter to the mutation, which is a common requirement. 作为奖励,该功能允许将参数传递给突变,这是一个常见的要求。

Your code changes would be: 您的代码更改将是:

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

The call within your component is just changeModel() - mapMutations is taking care of injecting the commit parameter. 组件中的调用只是changeModel() - mapMutations正在处理注入commit参数。

Note, I am not sure this is adding much except some extra noise (compared to a simple this.$store.commit() ), but perhaps your requirement is more complicated than the example code. 注意,我不确定除了一些额外的噪音之外this.$store.commit()增加很多(与简单的this.$store.commit()相比this.$store.commit() ),但也许你的要求比示例代码更复杂。

It is not exaclty the solution that you asked but its effect is the same. 你提出的解决方案并不是很好,但效果是一样的。 As the mutation is a variable parameter, it is obvious to put it into a function as an input parameter instead of changing the mutation name. 由于变异是一个可变参数,很明显将其作为输入参数放入函数而不是更改变异名称。 I would create an action in the store like this: 我会在商店中创建一个动作,如下所示:

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

And I would use this action in the component passing the mutationName into it. 我会在将mutationName传递给它的组件中使用此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM