Axios post request with multiple parameters in vuex action

时光总嘲笑我的痴心妄想 提交于 2019-12-11 04:13:17

问题


Fetching API data with axios in vuex action:

actions: {
login ({commit}, payload) {
  axios.post(globalConfig.TOKEN_URL, {
    payload
  })
    .then((resp) => {
      commit('auth_success', resp.data)
    })
    .catch((err) => {
      console.log(err)
    })
},
}

Component's method for sending the data:

methods: {
  authChatClient () {
    let payload = {
      name: this.clientFio,
      number: this.clientNumber
    }
    this.$store.dispatch('login', payload)
  },
}

However it won't work, since payload is an object, wrapped in a payload object. Is it possible to send multiple parameters from component's method to a vuex action?

Post request is looking like this: payload: {name: "aaa", number: "111"}


回答1:


Vuex only allows the use of 1 parameter to an action. However, if I understand your question correctly, you can send multiple parameters to a vuex action if they are wrapped in an object. Example:

login({commit}, {name, number /*, ...more here*/}) {
    axios.post(globalConfig.TOKEN_URL, {
        name: name,
        number: number,
        /* more parameters here */
    })
    /* ... */
}

And you can call it with:

methods: {
  authChatClient () {
    let payload = {
      name: this.clientFio,
      number: this.clientNumber,
      /* more parameters */
    }
    this.$store.dispatch('login', payload)
  },
}


来源:https://stackoverflow.com/questions/53517078/axios-post-request-with-multiple-parameters-in-vuex-action

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!