Vue Axios动态网址 [英] Vue Axios Dynamic URL

查看:223
本文介绍了Vue Axios动态网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是动作:

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"

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

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

具体是产品ID

有什么建议吗?

推荐答案

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

Use the state from the context passed to your action.

例如

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,尤其要注意撰写动作部分.

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

请注意,我使用的是模板文字格式化URL字符串.这相当于

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)

这篇关于Vue Axios动态网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆