【问题标题】:How to pass an argument to functions mapped using ...mapActions(...)?如何将参数传递给使用 ...mapActions(...) 映射的函数?
【发布时间】:2017-04-16 02:27:26
【问题描述】:

考虑以下段落

export default {
  methods: {
    ...mapActions(["updateData", "resetData"]);
  }
}

我想将一个参数传递给被调用的函数。在保留...mapAction() 调用的同时不确定如何正确执行此操作,我不得不重写以下内容。

export default {
  methods: {
    // ...mapActions(["updateData", "resetData"])
    updateData: function() { this.$store.dispatch("updateData", "names") },
    resetData: function() { this.$store.dispatch("resetData"); }
  }
}

这是唯一的方法吗?

【问题讨论】:

    标签: javascript ecmascript-6 vue.js


    【解决方案1】:

    您可以将参数传递给调用它的方法。您只能发送一个参数,该参数将在操作中可用。使用mapActions时不需要做任何特别的事情

    例如你可以这样称呼它:

    <button @click=updateData({data1: 1, data2: 2})>
    

    在 vuex 商店中:

    const actions = {
      updateData: (state, data) => {
         //You will get passed parameter as data here
      },
    

    你仍然可以使用 mapActions:

    export default {
      methods: {
        ...mapActions(["updateData", "resetData"]);
      }
    }
    

    查看工作小提琴here:您可以在警报中看到传递的参数:)


    这里是mapActionsvuex repo的实现

    export function mapActions (actions) {
      const res = {}
      normalizeMap(actions).forEach(({ key, val }) => {
        res[key] = function mappedAction (...args) {
          return this.$store.dispatch.apply(this.$store, [val].concat(args))
        }
      })
      return res
    }
    

    你可以看到它接受 args 传递并将它们作为调度函数的第二个参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2021-07-28
      相关资源
      最近更新 更多