如何将数据从我的 vue 组件传递到商店?
这是我的组件:
methods: {
...mapActions('NavBar', [
'fix',
]),
onClick: function() {
this.fix('my-data');
},
....
在商店里:
actions: {
fix: ({ commit }) => {
//get data here?
},
},
最佳答案
VueJS 2.x 中的 Actions 和 Mutations 可以使用一个额外的参数(通常称为 payload
)和额外的数据。
来自VueJS documentation on Mutations :
You can pass an additional argument to store.commit, which is called the payload for the mutation:
mutations: {
increment (state, n) {
state.count += n
}
}
store.commit('increment', 10)
In most cases, the payload should be an object so that it can contain multiple fields, and the recorded mutation will also be more descriptive:
mutations: {
increment (state, payload) {
state.count += payload.amount
}
}
store.commit('increment', {
amount: 10
})
对于 Actions :
Actions support the same payload format and object-style dispatch:
// dispatch with a payload
store.dispatch('incrementAsync', {
amount: 10
})
// dispatch with an object
store.dispatch({
type: 'incrementAsync',
amount: 10
})
文档似乎不太清楚如何定义操作,但看起来以下内容应该有效:
actions: {
incrementAsync ({ commit, state }, payload) { ... }
}
关于vue.js - 将数据传递给商店?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45307344/