将数据传递到商店?

时间:2017-07-25 15:14:41

标签: vue.js vuejs2 vuex

如何将数据从我的vue组件传递到商店?

这是我的组件:

methods: {
    ...mapActions('NavBar', [
        'fix',
    ]),
    onClick: function() {
        this.fix('my-data');
    },
    ....

在商店里:

actions: {           
   fix: ({ commit }) => {
    //get data here?
   },
},

1 个答案:

答案 0 :(得分:6)

VueJS 2.x中的动作和变异可以带一个额外的参数(通常称为payload)和其他数据。

来自VueJS documentation on Mutations

  

您可以将另一个参数传递给调用的store.commit   突变的有效载荷:

mutations: {
  increment (state, n) {
    state.count += n
  }
}
store.commit('increment', 10)
  

在大多数情况下,有效负载应该是一个对象,以便它可以包含   多个字段,记录的变异也会更多   描述:

mutations: {
  increment (state, payload) {
    state.count += payload.amount
  }
}
store.commit('increment', {
  amount: 10
})

对于Actions

  

Actions支持相同的有效负载格式和对象样式分派:

// dispatch with a payload
store.dispatch('incrementAsync', {
  amount: 10
})

// dispatch with an object
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

关于如何定义操作的文档似乎不是很清楚,但看起来应该如下:

actions: {
  incrementAsync ({ commit, state }, payload) { ... }
}
相关问题