平常调用后端接口传参都是json对象,当提交表单遇到有附件需要传递时,通常是把附件上传单独做个接口,也有遇到后端让提交接口一并把附件传递到后端,这种情况需要把参数转成formData的数据,需要用到new FormData()。json对象转formData,一个一个的赋值代码会非常冗余,并且遇到复杂的数据结构,还需要一层一层的往下循环赋值。因此写了一个demo解决当前问题以供参考,写的不好的地方欢迎指正。
<template>
<div>
测试页面
<el-button type="primary" size="small" @click="changeHandle"
>json对象转formData</el-button
>
</div>
</template>
<script>
export default {
name: "test",
data() {
return {};
},
methods: {
changeHandle() {
let obj = {
name: "yongqiang.chen",
age: 30,
likes: ["足球", "篮球", "乒乓球"],
work: {
address: "软件园C5",
floor: 7,
isWork: true,
computer: {
color: "black",
num: 8,
size: 1024,
},
},
deepArray: [
[
{ name: "张三", age: 25, likes: ["七星彩", "大乐透", "双色球"] },
{ name: "李四", age: 26, likes: ["轿车", "摩托车", "自行车"] },
],
[
{ title: "隐形的翅膀", singer: "张韶涵" },
{ title: "2002年的第一场雪", singer: "刀郎" },
],
],
};
let formDatas = new FormData();
this.makeFormData(obj, formDatas);
for (let [name, value] of formDatas) {
console.log(`${name} = ${value}`);
}
},
makeFormData(obj, form_data) {
var data = [];
if (obj instanceof File) {
data.push({ key: "", value: obj });
} else if (obj instanceof Array) {
for (var j = 0, len = obj.length; j < len; j++) {
var arr = this.makeFormData(obj[j]);
for (var k = 0, l = arr.length; k < l; k++) {
var key = !!form_data ? j + arr[k].key : "[" + j + "]" + arr[k].key;
data.push({ key: key, value: arr[k].value });
}
}
} else if (typeof obj == "object") {
for (var j in obj) {
var arr = this.makeFormData(obj[j]);
for (var k = 0, l = arr.length; k < l; k++) {
var key = !!form_data ? j + arr[k].key : "." + j + "" + arr[k].key;
data.push({ key: key, value: arr[k].value });
}
}
} else {
data.push({ key: "", value: obj });
}
if (!!form_data) {
// 封装
for (var i = 0, len = data.length; i < len; i++) {
form_data.append(data[i].key, data[i].value);
}
return form_data;
} else {
return data;
}
},
},
};
</script>
<style>
</style>