点击+号,增加form表单的子级应该怎么做能实现?

点击+号,增加form表单的子级应该怎么做能实现?
上面的图片是ui图,这是一个编辑弹窗里面的功能,用的是vue2+element ui
在入参字段下面的表单,点击右侧的加号就能添加一个子级,总共能有三级。点击减号能删除当前的子级。
这七个表单的布局,是应该写七个form-item,还是在一个form-item下面写七个input,哪个好一点呢。
请问这样的添加表单的子级应该怎么实现呢? 求指导 求指导


回答:

组件

<!-- formRow.vue -->

<template>

<div>

<div class="form-row">

<el-form-item label="用户名">

<el-input

v-model="value.userName"

placeholder="请输入用户名"

></el-input>

</el-form-item>

<el-form-item label="密码">

<el-input

v-model="value.password"

placeholder="请输入密码"

></el-input>

</el-form-item>

<el-button @click="addChildren(value)"> 添加 </el-button>

<el-button @click="deleteRow(value)"> 删除 </el-button>

</div>

<div style="margin-left: 20px">

<template v-for="(item, index) in value.children">

<form-row

v-model="value.children[index]"

:key="index"

:index="index"

@removeRow="removeRow"

></form-row>

</template>

</div>

</div>

</template>

<script>

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);

}

},

},

};

</script>

<style>

.form-row {

display: flex;

margin-bottom: 10px;

}

.form-row .el-button {

height: 40px;

margin-left: 10px;

}

</style>

使用

<template>

<div id="app">

<el-form label-width="80px">

<template v-for="(item, index) in formArray">

<formRowVue

v-model="formArray[index]"

:key="index"

:index="index"

@removeItem="removeItem"

></formRowVue>

</template>

</el-form>

</div>

</template>

<script>

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);

}

}

},

};

</script>

<style lang="less">

</style>


回答:

七个form-item吧,往数组里面push呗

以上是 点击+号,增加form表单的子级应该怎么做能实现? 的全部内容, 来源链接: utcz.com/p/935055.html

回到顶部