如何将参数传递给使用... mapActions(...)映射的函数?

Kon*_*ten 7 javascript ecmascript-6 vue.js

考虑以下段落

export default {
  methods: {
    ...mapActions(["updateData", "resetData"]);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

这是唯一的方法吗?

Sau*_*abh 10

您只需将参数传递给调用它的方法即可.您只能发送一个参数,该参数将在操作中可用.使用时无需做任何特殊操作mapActions

例如,您可以将其称为:

<button @click=updateData({data1: 1, data2: 2})>
Run Code Online (Sandbox Code Playgroud)

并在vuex商店:

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

你仍然可以使用mapActions:

export default {
  methods: {
    ...mapActions(["updateData", "resetData"]);
  }
}
Run Code Online (Sandbox Code Playgroud)

看到工作提琴在这里:你可以看到传递的参数在警告:)


下面是执行mapActionsvuex回购

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
}
Run Code Online (Sandbox Code Playgroud)

您可以看到它接受args传递并将它们作为dispatch函数的第二个参数.