實現(xiàn)效果,avue-crud新增按鈕的表單彈窗,自定義表單手動添加/刪除

image.png
1. html代碼
<avue-crud
:option="option"
:before-open="beforeOpen"
v-model="form"
@row-save="rowSave"
...其他省略
>
<!-- 自定義字段的表單slot -->
<template slot="customOpenForm">
<div class="custom-list-container">
<el-form-item>
<el-button
type="primary"
icon="el-icon-plus"
@click="handleCrudAdd"
:disabled="crudType == 'view'"
size="small">
新增
</el-button>
</el-form-item>
<el-form-item
v-for="(item, index) in form.addList"
:key="index"
:label="`輸入框 ${index + 1}`"
class="custom-item">
<div style="display: flex; align-items: center; gap: 10px;">
<el-input
v-model="form.addList[index].intValue"
placeholder="請輸入內(nèi)容"
style="flex: 1;">
</el-input>
<el-button
type="danger"
icon="el-icon-delete"
size="small"
circle
@click="handleCrudDel(index)"
v-if="form.addList.length > 1 && crudType != 'view'">
</el-button>
</div>
</el-form-item>
</div>
</template>
</avue-crud>
2. js代碼
form: {
addList: [
{
intValue: ''
}
]
},
option: {
column: [
{
label: "姓名",
prop: "name",
rules: [{
required: true,
message: "請輸入賬號姓名",
trigger: "blur"
}]
},
{
label: '自定義',
prop: 'customOpen',
hide: true, // 隱藏默認(rèn)的表單控件
slot: true, // 開啟自定義
rules: [{
required: true,
validator: (rule, value, callback) => {
let values = this.form.addList;
if (!values || values.length === 0) {
callback(new Error('至少需要一個項目'));
} else if (values.some(item => !item.intValue || item.intValue.trim() === '')) {
callback(new Error('所有項目都必須填寫'));
} else {
callback();
}
},
trigger: 'blur'
}]
}
]
},
3. 方法
// 增加的方法
// 新增項目
handleCrudAdd() {
this.form.addList.push({
intValue: ''
});
},
// 刪除項目
handleCrudDel(index) {
if (this.form.addList.length > 1) {
this.form.addList.splice(index, 1);
} else {
this.$message.warning('至少需要保留一個項目');
}
},
// beforeOpen方法內(nèi)增加的內(nèi)容
beforeOpen(done, type) {
this.crudType = type;
if (type === 'add') {
this.form.addList = [
{
intValue: ''
}
]
}
done();
...其他省略
},
- 提交表單格式
// rowSave方法返回的row,格式為
{
name: '張三',
addList: [
{ intValue: 1 },
{ intValue: 2 },
{ intValue: 3 },
]
}