Vue Axios Dynamic URL

2019-07-30 17:34发布

问题:

I would like to dynamically create the URL path for my axios post action in my vue.js application

Here is the action:

editProduct: function ({dispatch, commit}, payload) {
  axios
    .put('http://localhost:8081/product/5b5ca691e4f0d93c18e3f6d9', payload)
    .then(res => dispatch('loadProducts', res.data))
    .catch(function (error) {
      console.log(error)
    })
    .then(() => {
      commit('clearAddEditProduct')
    })
}

I would like to replace the "5b5ca691e4f0d93c18e3f6d9" with whatever is in the state

state: { // data
product: {
  name: '',
  description: '',
  externalid: '',
  active: '',
  id: ''
}

Specifically the Product ID

Any suggestions?

回答1:

Use the state from the context passed to your action.

For example

editProduct: function ({dispatch, commit, state}, payload) {
  // note the return below. This lets you compose actions
  return axios
    .put(`http://localhost:8081/product/${encodeURIComponent(state.product.id)}`, payload)
     // etc

See https://vuex.vuejs.org/guide/actions.html and in particular, note the Composing Actions section.


Note that I'm using a template literal to format the URL string. This is the equivalent of

'http://localhost:8081/product/' + encodeURIComponent(state.product.id)