George George
George George

Reputation: 601

Vuejs simplify vuex action call

I am calling a store action through a component like:

sublitPost(){
    this.$store.dispatch({type:"submitPost", userPost:this.newPost});
}

and the store action looks like this:

  actions: {
    submitPost({commit, state}, userPost: any) {
     /...rest code here

Although, I would like to simplify this and call the action like:

sublitPost(){
    this.$store.dispatch("submitPost", this.newPost);
}

What is the tweak in the action's signature I have to do? What I've tried is to have the action like:

  actions: {
        submitPost(userPost: any) {
          console.log({userPost})
         /...rest code here

but in this case, the received object doesn't look correct. What I get in the console log is: enter image description here

Any help is welcome

Upvotes: 0

Views: 198

Answers (2)

Shivam Bisht
Shivam Bisht

Reputation: 434

I have divided my store into modules so I am exporting my all mutations, actions, getters. I am committing a mutation from my action with payload,here payload is an object with property currentWidth

export function fetchDeviceCurrentWidth ({ commit, state }, payload) {
  commit('updateDeviceCurrentWidth', payload)
}

My mutation

export function updateDeviceCurrentWidth (state, payload) {
  state.currentDeviceWidth = payload.currentWidth
}

My getter

export const currentDeviceWidth = state => state.currentDeviceWidth

This is from where I am dispatching an action:

myEventHandler () {
      this.$store.dispatch('fetchDeviceCurrentWidth', {
        currentWidth: window.innerWidth
      })
    }

There are many ways to use vuex store, but I like to break store into modules depending on features or Components.

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14904

You should change your syntax:

actions: {
    submitPost(state, data) {
      console.log(data)
    {

Upvotes: 2

Related Questions