要实现的效果如下图所示:
场景描述:
左边输入框输入key值,右边输入框输入value值,点加号会生成一条数据,点叉号会删除一条数据,每次生成的一条数据都在前一条生成数据的后面
代码如下:
<template>
<div class="home">
<div style="width: 400px">
<el-form ref="form" :model="form" label-width="80px">
<template v-for="(arg, i) in argList">
<div :key="i">
<el-form-item :label="arg.name" style="display: flex">
<div style="display: flex">
<div>{{ arg.value }}</div>
<div
class="el-icon-circle-close"
style="margin: 13px 0 0 88px"
@click="removeArg(arg)"
></div>
</div>
</el-form-item>
</div>
</template>
<el-row style="display: flex">
<el-form-item label="活动名称">
<template #label>
<el-input
size="mini"
v-model="form.name"
placeholder="属性"
></el-input>
</template>
<el-input
size="mini"
v-model="form.value"
placeholder="值"
></el-input>
</el-form-item>
<div
class="el-icon-circle-plus-outline"
style="margin: 12px 0 0 10px"
@click="addArg(form)"
></div>
</el-row>
</el-form>
</div>
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
form: {
name: "",
value: "",
},
argList: [],
};
},
mounted() {
this.fetchInfo();
},
methods: {
//模拟调详情接口回显数据
fetchInfo() {
let vm = this;
//模拟后台数据的一部分
let data = {
attribtue: '{\"aaa\":\"bbb\"}',
id: "1234567654323456",
};
//回显argList
vm.argList = ((attrs) => {
let res;
res = [];
for (let name in attrs) {
res.push({
name,
value: attrs[name],
});
}
return res;
})(JSON.parse(data.attribtue));
},
//提交表单,调接口将数据传给后台
submit() {
let vm = this;
return new Promise((resolve, reject) => {
let alias;
let props;
let params;
alias = vm.isNew
? "cmb-realtime-sourceVirtual-addSource"
: "cmb-realtime-sourceVirtual-editSource";
params =
(!vm.isNew && {
id: vm.obj.id,
}) ||
{};
props = {
attribtue: ((argList) => {
let res;
res = {};
argList.forEach((arg) => {
res[arg.name] = arg.value;
});
return JSON.stringify(res);
})(vm.argList),
dataSourceId: vm.form.dataSourceId
//...其他参数
};
vm.api.doRequest({
alias,
body: props,
params,
}).then((res) => {
if(res.code == 0) {
//...新增或编辑成功后需要做的操作
return resolve();
}
return resolve();
})
});
},
//删除表单项
removeArg(arg) {
let vm = this;
vm.argList = vm.argList.filter(
(argItem) => argItem.name !== arg.name
);
},
//添加表单项
addArg(form) {
let vm = this;
function clearAddingForm() {
vm.form.name = "";
vm.form.value = "";
}
if (!form.name || !form.value) return;
if (vm.argList.some((argItem) => argItem.name === form.name)) {
vm.argList.find((argItem) => argItem.name === form.name).value =
form.value;
clearAddingForm();
return;
}
vm.argList.push({ ...form });
vm.$nextTick(() => {
clearAddingForm();
});
},
},
};
</script>