组件
添加
删除
export default {
name: "form-row",
model: {
prop: "value",
event: "change",
},
props: {
value: {
type: Object,
default: () => [],
},
index: {
type: Number,
default: 0,
},
},
watch: {
value: {
handler(val) {
this.$emit("change", val);
},
deep: true,
},
},
methods: {
// 添加子级
addChildren() {
if (!this.value.children) {
this.$set(this.value, "children", [{ userName: "" }]);
} else {
this.value.children.push({
userName: "",
password: ""
});
}
},
// 删除该行表单
deleteRow() {
// 抛出事件到父级执行
this.$emit("removeRow", this.index);
},
// 删除子级
removeRow(index) {
if (this.value?.children[index]?.children?.length > 0) {
alert('请先删除子级')
} else {
this.value.children.splice(index, 1);
}
},
},
};
.form-row {
display: flex;
margin-bottom: 10px;
}
.form-row .el-button {
height: 40px;
margin-left: 10px;
}
使用
import formRowVue from './views/formRow.vue';
export default {
name: "myform",
components: {
formRowVue
},
data() {
return {
formArray: [
{
userName: "张三",
password: '123456',
children: [{ userName: "张三1", password: '123456' }, { userName: "张三2", password: '123456' }],
},
]
}
},
methods: {
removeItem(index) {
if (this.formArray[index]?.children?.length > 0) {
alert('请先删除子级')
} else {
this.formArray.splice(index, 1);
}
}
},
};