是值得的权力ENL

问题描述 投票:1回答:1

我想在我的vue.js应用程序中动态创建axios post动作的URL路径

这是行动:

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')
    })
}

我想用状态中的任何东西替换“5b5ca691e4f0d93c18e3f6d9”

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

特别是产品ID

有什么建议?

vue.js axios vuex
1个回答
0
投票

使用传递给您的操作的上下文中的state

例如

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

请参阅https://vuex.vuejs.org/guide/actions.html,特别是请注意Composing Actions部分。


请注意,我使用template literal格式化URL字符串。这相当于

'http://localhost:8081/product/' + encodeURIComponent(state.product.id)
© www.soinside.com 2019 - 2024. All rights reserved.