我想在我的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
有什么建议?
使用传递给您的操作的上下文中的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)