elementUI中的表单相关问题
一、用法
1、动态表单
调用接口返回表单,后端的接口返回值如下:
这些是渲染后的效果
页面使用(父组件)
<el-button size="small" class="Cancelbtn" @click="sub(true)">发起新的</el-button>
<!-- 弹窗-新的 -->
<el-dialog
style="margin-top: -10vh"
class="newdialogVisible"
:visible.sync="dialogVisible"
width="90%"
>
<div class="dialog-header">
{{ BpmName.appname }}
</div>
<div class="center">
<FromHead ref="FromHead" :List="List"></FromHead>
</div>
<div class="dialog-footer" align="center">
<div
style="display: inline; margin: 0 5px"
v-for="(obj, j) in List.button"
:key="j"
>
<el-button
v-if="obj.type === 0"
size="small"
class="Cancelbtn"
@click="sub(true)"
>{{ obj.name }}</el-button
>
<el-button
v-if="obj.type === 1"
size="small"
class="addbtn"
@click="sub(false)"
>{{ obj.name }}</el-button
>
</div>
</div>
</el-dialog>
<script>
import { mapGetters } from "vuex";
import {
GetHomeData,
BpmGetList,
GetFrom,
GetFromData,
AddFromData,
} from "@/api/Bpm";
import FromHead from "@/components/FromHead/index.vue";
export default {
name: "Process",
computed: {
...mapGetters(["userid", "name"]),
},
components: { FromHead },
data() {
return {
dialogVisible:false,
BpmName: {}, //从常用中携带的项目信息
List: {}, //新的获取动态表单,以及相关信息
newform: {
fromid: 1, //表单编号
node_uuid: "", //当前节点 保存数据时提交使用
jsondata: "", //动态表单searchList
sqr_id: 1, //申请人编号
sqr: "", //申请人姓名
draft: false, //是否是草稿
}, //表单提交
table: [], //表单中的表头
table1: [], //表单中的表格
vDisable: false,
}
},
created() {
const a = JSON.parse(localStorage.getItem("Goprocess"));
this.BpmName = a;
this.form.appid = this.BpmName.id;
},
methods: {
add() {
GetFrom({ appid: this.userid }).then((res) => {
res.data.dom.forEach((i) => {
//处理表格
if (i.type === 7) {
// 表头
i.table = i.attr.map((i, j) => {
return {
label: i,
prop: "a" + [j],
};
});
if (i.default_val.length > 0) {
i.table1 = i.default_val.filter(function (item, index, arr) {
return index != 0;
});
} else {
i.table1 = [];
}
}
});
const a = JSON.stringify(res.data);
this.List = JSON.parse(a);
// //这是为了表格中表单的验证,如果不需要则删除这两行,并把table和table1传递给组件EditFrom
// this.List.table = this.table; //<EditFrom v-else style="width: 69vw" :List="editForm" :table="table" :table1="table1"></EditFrom>
// this.List.table1 = this.table1; //把组件中表格的验证给去除掉
console.log(this.List, "新建表单");
localStorage.setItem("formList", JSON.stringify(this.List)); //为了离开弹窗时,检查是否有所改变
this.dialogVisible = true;
});
},
}
}
</script>
封装动态表单(子组件)
我没有把按钮封装在这里面,因为按钮是需要在父组件中的
<template>
<div id="SearchHead">
<el-form
:inline="true"
style="width: 100%; height: 100%"
ref="FromHead"
:model="List"
label-width="200px"
label-position="top"
>
<el-row :gutter="12" style="width: 100%; display: flex; flex-wrap: wrap">
<el-col :span="12" v-for="(item, index) in List.dom" :key="index">
<el-form-item
v-if="item.type === 0"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="item.required ? item.required : { required: false }"
>
<el-input
v-model="item.default_val"
placeholder="请输入"
></el-input>
</el-form-item>
<el-form-item
v-if="item.type === 1"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="item.required ? item.required : { required: false }"
>
<el-input-number
v-model="item.default_val"
placeholder="请输入"
></el-input-number>
</el-form-item>
<el-form-item
v-if="item.type === 2"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="item.required ? item.required : { required: false }"
>
<el-select v-model="item.default_val" placeholder="请选择">
<el-option
v-for="(i, ind) in item.attr"
:key="ind"
:label="i"
:value="i"
>
</el-option>
</el-select>
</el-form-item>
<el-form-item
v-if="item.type === 3"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="item.required ? item.required : { required: item.required }"
>
<el-date-picker
v-model="item.default_val"
type="date"
placeholder="选择日期"
format="yyyy-MM-dd"
>
</el-date-picker>
</el-form-item>
<el-form-item
v-if="item.type === 4"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="item.required ? item.required : { required: false }"
>
<el-date-picker
v-model="item.default_val"
type="datetime"
placeholder="选择日期时间"
>
</el-date-picker>
</el-form-item>
<el-form-item
v-if="item.type === 5"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="item.required ? item.required : { required: false }"
>
<el-radio-group v-model="item.default_val">
<el-radio :label="ii" v-for="ii in item.attr" :key="ii">{{
ii
}}</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item
v-if="item.type === 6"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="
item.required
? {
required: item.required.required,
message: item.required.message,
trigger: 'blur',
}
: { required: false }
"
>
<el-checkbox-group v-model="item.default_val">
<el-checkbox
:label="jj"
v-for="jj in item.attr"
:key="jj"
></el-checkbox>
</el-checkbox-group>
</el-form-item>
<el-form-item
v-if="item.type == 8"
:label="item.name"
:prop="'dom.' + index + '.default_val'"
:rules="[
item.required
? {
required: item.required.required,
message: item.required.message,
trigger: 'change',
}
: { required: false },
]"
>
<el-upload
class="upload-demo"
action="#"
ref="upload"
multiple
:file-list="item.attr"
:on-change="
(file, fileList) => {
change(file, fileList, index);
}
"
:auto-upload="false"
:http-request="httprequest"
:on-remove="remove"
accept=".xlsx,.xls,.jpg,.jpeg,.gif,.png,.pdf,.doc,.docx"
>
<el-button
slot="trigger"
icon="el-icon-upload2"
style="width: 100%; text-align: left"
size="small"
class="dashedbtn"
>上传文件</el-button
>
</el-upload>
</el-form-item>
</el-col>
</el-row>
<el-row :gutter="24" style="width: 100%; display: flex; flex-wrap: wrap">
<el-col :span="24" v-for="(item, index) in List.dom" :key="index">
<el-form-item v-if="item.type == 7" :label="item.name">
<el-button
v-if="item.type == 7"
size="small"
@click="addtable(item)"
class="addbtn"
>添加行</el-button
>
<el-button
v-if="item.type == 7"
size="small"
@click="deletetable(item)"
class="Cancelbtn"
>删除</el-button
>
<el-table
v-if="item.type == 7"
ref="table"
:data="item.table1"
border
style="width: 100%; margin-top: 1%"
:header-cell-style="{
padding: '0',
}"
@selection-change="handleSelectionChange"
>
<el-table-column type="selection" width="45" align="center">
</el-table-column>
<el-table-column
v-for="(i, index) in item.table"
:key="i.label"
:prop="i.prop"
align="center"
:label="i.label"
>
<template slot-scope="scope">
<el-input
size="small"
v-model="scope.row[index]"
placeholder="请输入"
/>
</template>
</el-table-column>
</el-table>
</el-form-item>
</el-col>
</el-row>
</el-form>
</div>
</template>
<script>
import { UploadData } from "@/api/Equipment";
export default {
name: "SearchHead",
props: {
List: [Object, Array],
},
data() {
return {
multipleSelection: [], //多选
tableFormrules: [],
tableForm: {},
ta: [],
fileList: [], //文件列表
formData: new FormData(),
up: [],
};
},
methods: {
// // 一种方法
// sub(callback) {
// this.$refs["FromHead"].validate(async (valid) => {
// if (valid) {
// // const res = await AddFromData({ ...this.newform });
// // console.log(res);
// // if (res.code === 200) {
// // if (this.newform.draft) {
// // this.$notify({
// // type: "success",
// // position: "bottom-left",
// // message: "添加成功",
// // duration: 2000,
// // offset: 100,
// // });
// // } else {
// // this.$notify({
// // type: "success",
// // position: "bottom-left",
// // message: "暂存成功",
// // duration: 2000,
// // offset: 100,
// // });
// // }
// // }
// } else {
// this.$message.error("请将必填项填写完整");
// return false;
// }
// });
// },
// 验证表单 两种方法
validate(callback) {
this.$refs["FromHead"].validate((valid) => {
callback(valid);
});
},
resetFields() {
this.$refs["FromHead"].resetFields();
},
validateField(props, index) {},
// 上传文件验证
upload(rule, value, callback, i) {
// console.log(value);
if (i.default_val !== "" || i.default_val !== []) {
callback();
} else {
callback(new Error("请先上传相关文件"));
}
},
// 表格添加行
addtable(item) {
const lis = Array(item.table.length).fill("");
// lis=['','','','','','']
var ar = false;
// if (item.table1) {
item.table1.push(lis);
// } else {
// item.table1 = [];
// item.table1.push(lis);
// }
// 为了表格表单校验
// const aaa = lis.map((ele, ind) => {
// return "a" + [ind];
// });
// let obj = {}; //初始化js对象
// for (let i = 0; i < aaa.length; i++) {
// this.$set(obj, aaa[i], "");
// }
// this.List.table1.push(obj);
// this.List.table1.push(lis);
// // 判断表格最后一行是否都填完整
// if (this.table1.length > 0) {
// this.table1[this.table1.length - 1].forEach((item) => {
// if (item === "") {
// ar = true;
// } else {
// ar = false;
// }
// });
// if (ar) {
// this.$message.error("请将表格填写完整");
// } else {
// this.table1.push(lis);
// }
// } else {
// this.table1.push(lis);
// }
},
// 表格删除
deletetable(item) {
var da = [];
da = item.table1.filter((itemA) => {
return this.multipleSelection.every((itemB) => {
return itemB !== itemA;
});
});
this.table1 = da;
},
toggleSelection(rows) {
if (rows) {
rows.forEach((row) => {
this.$refs.table.toggleRowSelection(row);
});
} else {
this.$refs.table.clearSelection();
}
},
handleSelectionChange(val) {
this.multipleSelection = val;
console.log(this.multipleSelection);
},
// 导入
remove(file, fileList) {
this.fileList = fileList;
this.List.dom.forEach((i, j) => {
if (i.type === 8) {
i.default_val = this.fileList.map((item, index) => {
return item.FileUrl;
});
}
});
},
change(file, fileList, index) {
this.fileList = []; // 清空图片已经上传的图片列表(绑定在上传组件的file-list)
let a = 0;
fileList.forEach((item, idx) => {
/*在此处,对比文件名,将文件名相同的对比次数累加,
相同的文件名累加值为 2 时,说明文件名已经重复,直接删掉。*/
if (file.name === item.name) {
a++;
// console.log(a, file, fileList);
if (a === 2) {
this.$mess.info("不能重复上传,已把重复文件删除");
fileList.splice(idx, 1);
}
}
});
this.fileList = fileList;
if (a !== 2) {
this.httprequest(file, index);
}
},
async httprequest(file, index) {
// 一个一个上传
var formData = new FormData();
formData.append("files", file.raw);
const res = await UploadData(formData);
// console.log(res, "123");
if (res.code === 200) {
const a = [];
a.push(res.data[0].FileUrl);
this.List.dom.forEach((i, j) => {
if (i.type === 8 && j === index) {
i.default_val = a;
}
});
this.$mess.success("上传成功"); //这个是封装的,无论调用多少次,都只显示一次
}
},
},
};
</script>
<style lang="scss">
#SearchHead {
width: 100%;
.el-form-item {
width: 100%;
}
.el-form-item__content {
width: 100%;
}
.el-select {
width: 100%;
}
.el-textarea__inner {
border: 1px solid #dcdfe6 !important;
}
.el-date-editor.el-input {
width: 100%;
}
.el-upload {
width: 100%;
}
}
</style>
2、多个表单共用一个对象,但要同时验证
<template>
<div id="Detail" class="Detail">
<!-- 收样信息 -->
<div class="top">
<div
style="
display: flex;
justify-content: space-between;
border-bottom: 1px solid #e4e7ed;
margin-bottom: 20px;
"
>
<div class="titleBox">
<img src="@/assets/wd.png" style="width: 20px; height: 20px" />
<div>收样信息 Receiver Information</div>
</div>
</div>
<div class="formbox">
<el-form
:inline="false"
ref="formA"
:model="editformReceiver"
:rules="editformReceiverRules"
>
<el-form-item label="Name(收样名称)" prop="receivername">
<el-input v-model="editformReceiver.receivername"></el-input>
</el-form-item>
<el-form-item label="Address(收样地址)" prop="receiveraddress">
<el-input
v-model="editformReceiver.receiveraddress"
type="textarea"
></el-input>
</el-form-item>
<el-form-item
label="Contact person(联系人)"
prop="receivercontactperson"
>
<el-input
v-model="editformReceiver.receivercontactperson"
></el-input>
</el-form-item>
<el-form-item label="E-mail(邮箱)" prop="receiveremail">
<el-input v-model="editformReceiver.receiveremail"></el-input>
</el-form-item>
<el-form-item label="Phone(电话)" prop="receiverphone">
<el-input v-model="editformReceiver.receiverphone"></el-input>
</el-form-item>
</el-form>
</div>
</div>
<!-- 送样信息 -->
<div class="top">
<div
style="
display: flex;
justify-content: space-between;
border-bottom: 1px solid #e4e7ed;
margin-bottom: 20px;
"
>
<div class="titleBox">
<img src="@/assets/wd.png" style="width: 20px; height: 20px" />
<div>送样信息 Sender Information</div>
</div>
</div>
<div class="formbox">
<el-form
:inline="false"
ref="formB"
:model="editformReceiver"
:rules="editformReceiverRules"
>
<el-form-item label="Name(客户名称)" prop="sendername">
<el-input v-model="editformReceiver.sendername"></el-input>
</el-form-item>
<el-form-item label="Address(客户地址)" prop="senderaddress">
<el-input
v-model="editformReceiver.senderaddress"
type="textarea"
></el-input>
</el-form-item>
<el-form-item
label="Contact person(联系人)"
prop="sendercontactperson"
>
<el-input v-model="editformReceiver.sendercontactperson"></el-input>
</el-form-item>
<el-form-item label="E-mail(邮箱)" prop="senderemail">
<el-input v-model="editformReceiver.senderemail"></el-input>
</el-form-item>
<el-form-item label="Phone(电话)" prop="senderphone">
<el-input v-model="editformReceiver.senderphone"></el-input>
</el-form-item>
<el-form-item label="Way of Delivery(送样方式)">
<br />
<el-radio-group
v-model="editformReceiver.sendsampletype"
@change="changeRadio"
>
<el-radio :label="0">自送</el-radio>
<el-radio :label="1">赴厂</el-radio>
<el-radio :label="2">快递</el-radio>
</el-radio-group>
<br />
</el-form-item>
<el-form-item
label="快递单号"
v-if="editformReceiver.sendsampletype === 2"
>
<el-input v-model="editformReceiver.couriernumber"></el-input>
</el-form-item>
</el-form>
</div>
</div>
</div>
</template>
<script>
export default {
methods: {
// 提交
addsub() {
let formArr = ["formA", "formB", "formC"]; //三个form表单的ref
var resultArr = []; //用来接受返回结果的数组
var _self = this;
function checkForm(formName) {
//封装验证表单的函数
var result = new Promise(function (resolve, reject) {
_self.$refs[formName].validate((valid) => {
if (valid) {
resolve();
} else {
reject();
}
});
});
resultArr.push(result); //push 得到promise的结果
}
formArr.forEach((item) => {
//根据表单的ref校验
checkForm(item);
});
Promise.all(resultArr)
.then(async (values) => {
//提交表单的相关操作
//_self.$refs.editformReceiver.resetFields();
if (res.code === 200) {
_self.$message.success("提交成功");
_self.cancel();
} else {
_self.$message.error("提交失败");
}
})
.catch((_) => {
// _self.$message.error("请将必填项填写完整");
});
},
}
}
3、表单中的上传图片不显示
使用上传el-upload,若ruleForm没有原始数据,上传图片后,图片无法显示。只要把<el-form-item的绑定属性和<el-upload内部<img的属性设置为不同变量,上传完成后设置img的src即可。
4、输入框使用正则表达式进行实时校验,正则如正整数、负整数、整数、非负整数、浮点数等
@input事件
每输入一个字符都会触发该事件,可用于实时查询。
<el-input
v-model="day"
placeholder="请输入延期天数"
@input="input"
/>
使用方法:
methods: {
input(e) {
const num = /^[1-9]\d*$/
if (num.test(e)) {
this.day = e
} else {
// this.day = e.replace(/[^\d.]/g, '')
this.day = e.replace(e, '')
this.$message.error('延期天数只能输入正整数')
}
},
}
还有一些其他常用正则:
/^([1-9]|10)$/ //匹配1-10整数
^[1-9]\d*$ //匹配正整数
^-[1-9]\d*$ //匹配负整数
^-?[1-9]\d*$ //匹配整数
^[1-9]\d*|0$ //匹配非负整数(正整数 + 0)
^-[1-9]\d*|0$ //匹配非正整数(负整数 + 0)
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$ //匹配正浮点数
^-([1-9]\d*\.\d*|0\.\d*[1-9]\d*)$ //匹配负浮点数
^-?([1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0)$ //匹配浮点数
^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|0?\.0+|0$ //匹配非负浮点数(正浮点数 + 0)
^(-([1-9]\d*\.\d*|0\.\d*[1-9]\d*))|0?\.0+|0$ //匹配非正浮点数(负浮点数 + 0)
二、样式
1、输入框自动填充的背景色修改
进入登录页,账号和密码会自动填入时,会出现填充背景色,这个背景色和我们的页面样式不符合,需要改写成自己所需颜色。
//vue2
&:-webkit-autofill {
transition: background-color 5000s ease-in-out 0s;
background-color: transparent !important;
// box-shadow: 000px1000px $bg inset !important;
-webkit-text-fill-color: $cursor !important; //字体颜色
}
//vue3
input:-internal-autofill-selected {
transition: background-color 5000s ease-in-out 0s;
background-color: transparent !important;
}
2、日期图标显示在右侧
.el-input__inner {
border: 1px solid #496ef9;
width: 100%;
height: 30px;
line-height: 30px;
}
.el-date-editor.el-input {
width: 100%;
}
.el-input--small .el-input__inner {
width: 100%;
}
.el-input--small,
.el-input--suffix {
width: 100%;
}
// 日期图标
.el-input__prefix {
left: auto;
}
.el-icon-date:after {
content: '\e78e';
position: absolute;
right: 50px;
color: #496ef9;
}
.el-icon-date:before {
content: '';
}
// 日期清除键
.el-input__suffix {
display: none;
}
或者是
.el-date-editor.el-input {
width: 44%;
}
.el-input__prefix {
position: absolute;
top: 0;
right: 5px;
display: block;
width: 100%;
}
.el-icon-date:after {
content: '\e78e';
position: absolute;
top: 1px;
right: 30px;
color: #496ef9;
}
.el-icon-date:before {
content: '';
}
.el-input__icon {
width: 100%;
}
3、输入框提示文字的样式
.el-input__inner {
&::placeholder {
text-align: center;
}
}
这篇文章看完如果您觉得有所收获,认为还行的话,就点个赞收藏一下呗