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

标签 javascript ecmascript-6 vue.js

考虑以下段落

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"); }
  }
}

这是唯一的方法吗?

最佳答案

您可以只将参数传递给调用它的方法。您只能发送一个参数,该参数将在操作中可用。使用 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"]);
  }
}

参见工作 fiddle here : 你可以在警报中看到传递的参数:)


这是来自 vuex repomapActions 的实现

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 并将它们作为调度函数的第二个参数。

关于javascript - 如何将参数传递给使用 ...mapActions(...) 映射的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40910831/

相关文章:

javascript - 选中复选框 - 为变量分配值并发送提交

javascript - 未使用的 ES6 模块会影响性能吗?

javascript - 避免直接改变 prop

javascript - vue js - 找不到子组件模板

vue.js - 使用组合 API 从另一个组件调用函数

javascript - 如何在 Angular 服务中使用providedIn 'root'

javascript - 附加按钮输入并删除不工作的 parent

javascript - 这些ES6导入方式有什么区别?

javascript - React 中类外部的函数或变量

javascript - Express Router 读取两个不同的动态路由相同