Send data to the store?

How do I pass data from my vue component to the store?

Here's my component:

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

      

And in the store:

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

      

+3


source to share


1 answer


Actions as well as mutations in VueJS 2.x can take additional arguments (often called payload

) additional data.

From the VueJS documentation on mutations :

You can pass an additional argument to store.commit, which invokes the payload for the mutation:

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

      

In most cases, the payload must 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
})

      



And for 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
})

      

The documentation doesn't seem very clear as to how to define an action, but it looks like this:

actions: {
  incrementAsync ({ commit, state }, payload) { ... }
}

      

+5


source







All Articles