VueJs-如何使用axios设置动态参数



我有一个类似的案例

首先我从服务器获取数据,然后响应是

{
data: {
id: 4,
status: A,
items: {
child: [
{
id: 28,
product_id: 1
},
{
id: 33,
product_id: 4
}
]
}
},
status: 200,
error: 0
}

之后,我想要的数据响应将数组items.child作为POST中的参数发送。这是要在POST中设置的参数的格式:

item_id : data.id
item_status: data.status
item_combo_28_0: 1|0
item_combo_33_1: 4|1

item_combo是从响应数据中获取的动态参数

nb:item_combo_(child.id(_index:child.product_id |索引

这是我的axios代码

getData() {
let headers = {
Authorization: 'Bearer ' + window.accessToken
}
let id = val
axios({
method: 'GET',
url: BASE_API('productcombo/' + id),
headers: headers
})
.then(response => {
this.itemCombo = []
this.dataResponse = response.data.data
this.setItemPackage()
this.loading = false
})
.catch(error => {
this.loading = false
})
},
setItemPackage() {
if (this.dataResponse.items.child.length > 0) {
this.dataResponse.items.child.map((row, idx) => {
this.$set(row, 'item_combo_' + row.id + '_' + [idx], row.product_id + '|' + idx)
this.itemCombo.push(row)
console.log(this.itemCombo)
})
}
}

预期:如何在POST 的动态参数中设置(item_combo_?(的数组变量

这是我的邮政编码

sendData() {
this.loadingPackage = true
let headers = {
Authorization: 'Bearer ' + window.accessToken
}
let data = {
item_id: this.dataResponse.id,
item_tatus: this.dataResponse.status,
======= Here my expect =========
item_combo_27_0: 13 | 0,
item_combo_3_1: 15 | 0
================================
}
axios({
method: 'POST',
url: BASE_API('openorder/additemcombo'),
headers: headers,
data: data
})
.then(response => {
this.result = response.data
}
if (response.data.error) {
this.$message({
message: 'Error Network',
type: 'error'
})
}
})
.catch(() => {
this.$notify({
message: 'Error Connections',
type: 'warning'
})
})
},

我不太确定我是否正确理解您,但在setItemPackage函数中,您已经有了将responseData转换为变量的代码。因此,您只需要在sendData函数中使用它,即可创建将通过axios发送的对象。

sendData() {
this.loadingPackage = true
let headers = {
Authorization: 'Bearer ' + window.accessToken
}
let data = {
item_id: this.dataResponse.id,
item_tatus: this.dataResponse.status,
}
if (this.dataResponse.items.child.length > 0) {
this.dataResponse.items.child.map((row, idx) => {
data['item_combo_' + row.id + '_' + idx] = row.product_id + '|' + idx);
})
}
axios({
method: 'POST',
url: BASE_API('openorder/additemcombo'),
headers: headers,
data: data
})....

最新更新