【问题标题】:Vue Axios Dynamic URLVue Axios 动态 URL
【发布时间】:2019-02-12 06:12:12
【问题描述】:

我想在我的 vue.js 应用程序中为我的 axios 发布操作动态创建 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】:

    使用传递给您的操作的上下文中的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)
    

    【讨论】:

    猜你喜欢
    • 2022-11-10
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2020-10-11
    • 2019-10-22
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多