考虑以下段落
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 repo 的 mapActions
的实现
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/