Vuex - passing multiple parameters to mutation

后端 未结 3 1538
傲寒
傲寒 2020-12-02 08:53

I am trying to authenticate a user using vuejs and laravel\'s passport.

I am not able to figure out how to send multiple parameters to the vuex mutation via a

相关标签:
3条回答
  • 2020-12-02 09:19

    Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

    The easiest way to pass a number of parameters is to destruct them:

    mutations: {
        authenticate(state, { token, expiration }) {
            localStorage.setItem('token', token);
            localStorage.setItem('expiration', expiration);
        }
    }
    

    Then later on in your actions you can simply

    store.commit('authenticate', {
        token,
        expiration,
    });
    
    0 讨论(0)
  • 2020-12-02 09:24

    i think this can be as simple let as assume that you are going to pass multiple parameters to you action as you read up there actions accept only two parameters context and payload which is your data you want to pass in action so let take an example

    Setting up Action

    instead of

    actions: {
            authenticate: ({ commit }, token, expiration) => commit('authenticate', token, expiration)
        }
    

    do

    actions: {
            authenticate: ({ commit }, {token, expiration}) => commit('authenticate', token, expiration)
        }
    

    Calling (dispatching) Action

    instead of

    this.$store.dispatch({
                      type: 'authenticate',
                      token: response.body.access_token,
                      expiration: response.body.expires_in + Date.now()
                  })
    

    do

    this.$store.dispatch('authenticate',{
                      token: response.body.access_token,
                      expiration: response.body.expires_in + Date.now()
                  })
    

    hope this gonna help

    0 讨论(0)
  • 2020-12-02 09:29

    In simple terms you need to build your payload into a key array

    payload = {'key1': 'value1', 'key2': 'value2'}
    

    Then send the payload directly to the action

    this.$store.dispatch('yourAction', payload)
    

    No change in your action

    yourAction: ({commit}, payload) => {
      commit('YOUR_MUTATION',  payload )
    },
    

    In your mutation call the values with the key

    'YOUR_MUTATION' (state,  payload ){
      state.state1 = payload.key1
      state.state2 =  payload.key2
    },
    
    0 讨论(0)
提交回复
热议问题