多个循环的el-form-item的验证判断

<template>
    <div class="container">
        <el-drawer :title="title" :visible.sync="drawer" :wrapperClosable="false" size="40%"
            :before-close="handleClose">
            <el-form ref="form" :model="form" label-width="80px" :rules="rulesForm">
                <el-form-item label="布控名称" prop="taskName">
                    <el-input v-model="form.taskName" :disabled="disabled" class="ipt" maxlength="20" show-word-limit>
                    </el-input>

                </el-form-item>
                <el-form-item label="服务器" prop="algorithmDeviceId">
                    <el-select v-model="form.algorithmDeviceId" @change="fuwuqi" :disabled="disabled"
                        placeholder="请选择算法服务器">
                        <el-option v-for="(item, index) in suanfa" :key="index" :label="item.algorithmDeviceName"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="阈值">
                    <el-slider v-model="form.threshold" :disabled="disabled" show-input>
                    </el-slider>
                </el-form-item>
                <el-form-item label="布控时间">
                    <el-date-picker v-model="datastartEnd" type="datetimerange" :disabled="disabled"
                        start-placeholder="开始日期" end-placeholder="结束日期" :default-time="morenTime"
                        :picker-options="pickerOptions1" class="iptWidth" @change="dataTime">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <div style="max-height:40%;overflow-x: auto;margin-left: -9%;">
                <el-form ref="formlabels" style="margin-left: 11.5%" :inline="true" :model="formlabels" :rules="rules"
                    class="demo-form-inline" id="zhishiyin">
                    <div v-for="(item, index) in formlabels.videoInfoList" :key="index">
                        <el-form-item label="区域" :rules="rules.label" :prop="`videoInfoList.${index}.label`">
                            <el-cascader v-model="item.label" :disabled="disabled" :options="options" style="width:100%"
                                :props="props" clearable @change="handcheck($event, index)"></el-cascader>
                        </el-form-item>
                        <el-form-item label="摄像机" :rules="rules.content" :prop="`videoInfoList.${index}.content`">
                            <el-select v-model="item.content" @remove-tag="removetagcreame" :disabled="disabled"
                                multiple placeholder="请选择摄像机" class="iptWidth">
                                <el-option v-for="items in item.shex" :key="items.cameraId" :label="items.cameraName"
                                    :value="items.cameraId" @click.native="getDivision(items)">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <i @click="addlist(index)" v-show="disabledBtn" class="el-icon-circle-plus-outline"
                                style="color: green"></i>
                            <i @click="deletelist(item, index)" :v-show="disabledBtn" v-if="btndelte"
                                class="el-icon-remove-outline" style="color: red; margin-left: 20px"></i>
                        </el-form-item>
                    </div>
                </el-form>
                <div class="infos" v-if="yanzhenginfo">参数id不能填写相同,请注意!</div>
            </div>
            <div class="footBtn">
                <el-button type="primary" @click="onSubmit('form')" v-dbClick>确定</el-button>
                <el-button type="primary" @click="onerror" v-dbClick>取消</el-button>
            </div>
        </el-drawer>
    </div>
</template>

<script>
import { formatDate } from '../../../utils/tools.js';
import { isArray } from 'highcharts';
export default {
    data() {
        let validatelabel = (rule, value, callback) => {
            if (!value) {
                return callback();
            } else if (!/^[0-9A-Za-z]+$/.test(value)) {
                return callback(new Error('只允许输入大小写字母和数字'));
            } else {
                return callback();
            }
        };
        return {
            title: '新增布控',
            drawer: false,
            form: {
                taskName: '',
                algorithmDeviceId: '',
                //controlType: 1,
                threshold: 0,
                taskStartTime: '',
                taskEndTime: '',
                videoInfoList: {}
            },
            rulesForm: {
                taskName: [
                    { required: true, message: '请输入布控名称', trigger: 'blur' },
                    { min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }
                ],
                algorithmDeviceId: [{ required: true, message: '请选择服务器', trigger: 'change' }],
                //controlType:[{ required: true, message: '请选择布控类型', trigger: 'blur' }],
            },
            datastartEnd: [],
            morenTime: [],
            suanfa: [],

            formlabels: {
                videoInfoList: [
                    {
                        label: '',
                        content: [],
                        shex: [],
                    }
                ],

            },
            options: [],
            pickerOptions1: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                }
            },
            props: {
                label: 'title',
                value: 'id',
                checkStrictly: true
            },
            rules: {
                label: [{ required: true, message: '请选择区域', trigger: 'change' }],
                content: [{ required: true, message: '请选择摄像机', trigger: 'change' }]
            },
            btndelte: false,
            count: 0,
            yanzhenginfo: false,
            editadd: true,
            disabled: true,
            disabledBtn: false,
            resultArr: [],//接受验证返回结果数组
            formArr: ['form', 'formlabels'],//存放表单ref数组
        };
    },

    components: {},

    computed: {},
    props: {
        looksave: {
            type: Object,
            // 对象或数组默认值必须从一个工厂函数获取
            default() {
                return {};
            }
        }
    },
    mounted() {
        var myDate = new Date();
        var myHour = myDate.getHours(); //获取当前小时数(0-23)
        var myMinute = myDate.getMinutes(); //获取当前分钟数(0-59)
        var mySecond = myDate.getSeconds(); //获取当前秒数(0-59)
        var nowTime;
        nowTime = this.fillZero(myHour) + ':' + this.fillZero(myMinute) + ':' + this.fillZero(mySecond) + '  ';
        this.morenTime = [nowTime, nowTime];
        this.init()
    },
    watch: {
        looksave() {
            let that = this;
            let obj = {};
            obj = JSON.parse(JSON.stringify(that.looksave));
            console.log(obj)
            if (Object.keys(obj).length != 0) {
                let videoInfoList = []
                obj.algorithmDeviceId = Number(obj.algorithmDeviceId)
                this.datastartEnd = [obj.taskStartTime, obj.taskEndTime]
                if (obj.videoInfoList != null) {
                    obj.videoInfoList.forEach((item, idx) => {
                        videoInfoList.push({
                            label: item.label.split(',').map(Number),
                            content: item.content.split(',').map(Number),
                            shex: [],
                        })
                    })
                    videoInfoList.forEach(item => {
                        that.$api.get(
                            'camera/getRegionalVideoes',
                            { regionalId: item.label.join(',') },
                            (res) => {
                                if (res.code == 200) {
                                    item.shex = res.result
                                }
                            },
                            (err) => {
                                that.$message({
                                    message: err.message,
                                    type: 'error'
                                });
                            }
                        );
                    })
                    this.form = obj
                    this.formlabels.videoInfoList = videoInfoList
                } else {
                    this.form = obj
                    this.formlabels.videoInfoList = [
                        {
                            label: '',
                            content: [],
                            shex: [],
                        }
                    ]
                }

            } else {
                that.form = {}
                that.formlabels.videoInfoList = [
                    {
                        label: '',
                        content: [],
                        shex: [],
                    }
                ]
                that.$refs["form"].resetFields();
            }
        },
        'formlabels.videoInfoList.length': {
            handler(newValue, oldValue) {
                if (newValue > 1) {
                    this.btndelte = true;
                } else {
                    this.btndelte = false;
                }
            }
        },
    },

    methods: {
        fuwuqi() { },
        fillZero(str) {
            var realNum;
            if (str < 10) {
                realNum = '0' + str;
            } else {
                realNum = str;
            }
            return realNum;
        },
        init() {
            let params = {};
            this.$api.get(
                '接口',
                params,
                (res) => {
                    if (res.code == 200) {
                        let data = res.result;
                        this.options = data;
                    }
                },
                (err) => {
                    this.$message({
                        message: err.message,
                        type: 'error'
                    });
                }
            );
            this.$api.get(接口, {}, (res) => {
                if (res.code == 200) {
                    this.suanfa = res.result;
                }
            });

        },
        dataTime(val) {
            this.form.taskStartTime = formatDate(val[0]);
            this.form.taskEndTime = formatDate(val[1]);
        },
        handcheck(value, idx) {
            let params = value.join(',');
            this.$api.get(
                接口,
                { regionalId: params },
                (res) => {
                    if (res.code == 200) {
                        this.formlabels.videoInfoList[idx].content = []
                        // this.formlabels.videoInfoList.forEach(item => {
                        //     item.shex = res.result
                        // })
                        this.formlabels.videoInfoList[idx].shex=res.result
                    }
                },
                (err) => {
                    this.$message({
                        message: err.message,
                        type: 'error'
                    });
                }
            );
        },
        getDivision(val) {
            this.removetagcreame(val.cameraId);
        },
        //移除tag时触发
        removetagcreame(val) {
            let array2 = this.$store.state.savecreame;
            let result = [];
            if (array2.length != 0) {
                array2.forEach((item) => {
                    if (val == item.cameraId) {
                        //this.$store.state.savecreame.splice(item,1)
                    } else {
                        result.push(item);
                    }
                });
            }
            sessionStorage.setItem('linesgoback', JSON.stringify(result));
            this.$store.commit('linearc', result);
        },
        //封装验证函数
        checkForm(formName) {
            let _self = this;
            let result = new Promise(function (resolve, reject) {
                _self.$refs[formName].validate((valid) => {
                    if (valid) {
                        resolve();
                    } else { reject() }
                })
            })
            _self.resultArr.push(result) //push 得到promise的结果
        },
        onSubmit(form) {
            if (this.disabled == true) {
                this.drawer = false;
            } else {
                let _self = this;
                _self.formArr.forEach(item => { //根据表单的ref校验
                    _self.checkForm(item)
                })
                console.log(_self.resultArr)
                Promise.all(_self.resultArr).then(function (resolve, reject) { //都通过了
                    let params = Object.assign(_self.form, _self.formlabels);
                    params.videoInfoList.forEach(item => {
                        if (item.label != "") {
                            item.label = item.label.join(',')
                        }
                        if (item.content.length != 0) {
                            item.content = item.content.join(',')
                        }
                        delete item.shex
                    })
                    _self.$api.post(
                        '接口',
                        params,
                        (res) => {
                            if (res.code == 200) {
                                _self.drawer = false;
                                _self.$message({
                                    message: res.message,
                                    type: 'success'
                                });
                                _self.$emit('adddreave')
                            }
                        },
                        (err) => {
                            _self.$message({
                                message: err.message,
                                type: 'error'
                            });
                        }
                    );
                }).catch(err=>{
                    _self.resultArr=[]
                })
            
            }

        },
        suanfatype(formName) {
            let formslab = formName;
            let flag = 0;
            for (let i = 0; i < formslab.length; i++) {
                formslab[i].validate((valid, object) => {
                    if (valid == false) {
                        flag++;
                    }
                });
            }
            if (flag === 0) {
                let params = this.formlabels;
                let yanzheng = params.videoInfoList;
                const nameArr = yanzheng.map(function (item) {
                    return item.label;
                });
                const isDuplicate = nameArr.some(function (item, idx) {
                    return nameArr.indexOf(item) !== idx;
                });
                if (isDuplicate) {
                    this.yanzhenginfo = true;
                } else {
                    const returnedTarget = Object.assign(this.form, this.formlabels);
                    this.datasaves(returnedTarget);
                }
                this.$refs['form'].clearValidate();
                this.$refs['formlabels'].clearValidate();
            }
        },
        datasaves(params) {
            if (this.editadd) {
                this.$api.post(
                    '接口',
                    params,
                    (res) => {
                        console.log(res);
                        if (res.code == 200) {
                            this.dialogTableVisible = false;
                            this.$message({
                                message: res.message,
                                type: 'success'
                            });
                            this.$emit('suanfa');
                        }
                    },
                    (err) => {
                        this.$message({
                            message: err.message,
                            type: 'error'
                        });
                    }
                );
            } else {
                this.$api.put(
                    '接口',
                    params,
                    (res) => {
                        if (res.code == 200) {
                            this.dialogTableVisible = false;
                            this.$message({
                                message: res.message,
                                type: 'success'
                            });
                            this.$emit('suanfa');
                        } else {
                            this.$alert(`${res.message}`, '标题名称', {
                                confirmButtonText: '确定'
                            });
                        }
                    },
                    (err) => {
                        this.$message({
                            message: err.message,
                            type: 'error'
                        });
                    }
                );
            }
        },
        onerror() {
            this.drawer = false

            this.$refs.formlabels.clearValidate()
        },
        handleClose() {
            this.onerror()
        },
        addlist(index) {
            this.count++;
            this.formlabels.videoInfoList.push({
                label: '',
                content: [],
                shex:[]
            });

        },
        deletelist(item, index) {
            this.count--;
            if (this.formlabels.videoInfoList.length == 2) {
                this.count = 0;
            }
            this.formlabels.videoInfoList.splice(index, 1);
        },

    }
}

</script>

<style scoped>
.el-form {
    padding: 10px;
}

.footBtn {
    margin-left: 13%;
}

.ipt {
    width: 38%;
}
</style>

整个判断都在这里了,包括页面,都放这了,欢迎指导评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值