springboot+vue实现动态表单,嵌套自增自减表单,Excel导入

作为一名全栈工程师,难免会在工作中遇见很难搞的的功能,并且还要负责前端的页面,后端接口及数据库的编写。
分享一个功能,请看下列图片:
在这里插入图片描述
先说说功能效果,是否继承按钮代表着是它本身的数据,还是把数据改成它父类数据的。
输入框只能填写数字。
输入框后面有一个删除按钮,可以删除它所在的行的数据;读取excel是直接把数据导入表格里,不进行数据保存;添加一行会在下面添加一行新数据;删除一行,删掉最下面的数据;重置,清空是否继承按钮下的数据。点击下面的确定按钮后保存到数据库中。
话不多说,直接上代码,
删了一些隐私信息,但不影响这些功能的一些业务逻辑。

<template>
    <div>

        <!--头部功能-->
        <div class="pd-10">
            <el-button type="primary" @click="handAdd" style="margin-right: 10px">新增<i class="el-icon-circle-plus-outline"></i></el-button>
            <el-input style="width: 200px;" placeholder="" v-model="name" suffix-icon="el-icon-search"></el-input>
            <el-button class="ml-5" type="primary" @click="load" @keyup.native.enter="load">搜索</el-button>
            <el-button  type="warning" @click="reset">重置</el-button>
        </div>


        <!--数据表格-->
        <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"  @selection-change="handleSelectionChange">
            <el-table-column label="操作" width="200px">
                <template slot-scope="scope" >
                    <el-button type="success" @click="handleEdit(scope.row)">编辑<i class="el-icon-edit"></i></el-button>
                    <el-popconfirm
                            class="ml-5"
                            confirm-button-text='好的'
                            cancel-button-text='不用了'
                            icon="el-icon-info"
                            icon-color="red"
                            title="确定删除吗?"
                            @confirm="del(scope.row.id,scope.row.msg)"
                    >
                        <el-button type="danger"  slot="reference">删除<i class="el-icon-remove-outline"></i></el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!--分页-->
        <div style="padding: 10px 0">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageNum"
                    :page-sizes="[ 10, 15, 20,30]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <!--添加弹框-->
        <el-dialog title="" :visible.sync="dialogFormVisible"
                   width="40%">
            <el-form :model="form" :rules="rules" ref="addForm" >

                <el-form-item label="品牌" prop="brand">
                    <el-input v-model="form.brand" autocomplete="off"></el-input>
                </el-form-item>


                <el-form-item label="扭矩压力对照" ><br><br>
                </el-form-item>
                    <!--扭矩压力对照-->
                    <div>
                        <el-form v-for="ruleFormNL in ruleFormNL"  :model="ruleFormNL" label-width="100px" class="demo-ruleFormNL" >

                            <el-row>
                                <el-col :span="10">
                                    <el-form-item label="扭矩(NM):" prop="niuju">
                                        <el-input oninput ="value=value.replace(/[^0-9.]/g,'')" v-model="ruleFormNL.torque"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label="压力(BAR):" prop="yali">
                                        <el-input oninput ="value=value.replace(/[^0-9.]/g,'')" v-model="ruleFormNL.pressure"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="1">
                                    <el-button style="float: left " class="ml-10" type="danger" @click="reduceNj(ruleFormNL.id)" :disabled="flag">删除</el-button>
                                </el-col>

                            </el-row>

                            <el-divider></el-divider>
                        </el-form>
                        <el-form>
                            <el-form-item>
                                <!--                            <el-button type="primary" @click="submitFormAdd()">保存并关闭</el-button>-->
                                <el-upload

                                        action=""
                                        :on-change="handleChange"
                                        :show-file-list="false"
                                        :auto-upload="false"
                                        style="float: left;">
                                    <el-button  type="primary"
                                                style="float: left; margin-right: 10px"
                                    >读取excel文件</el-button>
                                </el-upload>
                                <el-button style="float: left" type="success" @click="add">添加一行</el-button>
                                <el-button style="float: left" type="danger" @click="reduce" :disabled="flag">删除一行</el-button>
                                <el-button style="float: left;margin-left: 10px" type="warning" @click="resetForm()">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>

<!--                <el-form-item label="备注" >-->
<!--                    <el-input v-model="form.remark" autocomplete="off"></el-input>-->
<!--                </el-form-item>-->

                <div style="margin: 10px 0; text-align: right">
                    <el-button  size="small" autocomplete="off" @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" size="small" autocomplete="off" @click="save">确定</el-button>
                </div>
            </el-form>

        </el-dialog>

        <!--修改弹框-->
        <el-dialog title="" :visible.sync="dialogFormVisibl"
                   width="40%">
            <el-form :model="form" :rules="rules" ref="editForm" >
                <el-form-item label="品牌" prop="brand">
                    <el-input v-model="form.brand" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="扭矩压力对照"><br><br>
                </el-form-item>

                    <!--扭矩压力对照-->
                    <div>
                        <el-form v-for="ruleFormNL in ruleFormNL"  :model="ruleFormNL" label-width="100px" class="demo-ruleFormNL">

                            <el-row>
                                <el-col :span="10">
                                    <el-form-item label="扭矩(NM):" prop="niuju">
                                        <el-input oninput ="value=value.replace(/[^0-9.]/g,'')" v-model="ruleFormNL.torque"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="10">
                                    <el-form-item label="压力(BAR):" prop="yali">
                                        <el-input oninput ="value=value.replace(/[^0-9.]/g,'')" v-model="ruleFormNL.pressure"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="1">
                                    <el-button style="float: left " class="ml-10" type="danger" @click="reduceNj(ruleFormNL.id)" :disabled="flag">删除</el-button>
                                </el-col>
                            </el-row>

                            <el-divider></el-divider>
                        </el-form>
                        <el-form>
                            <el-form-item>
                                <!--                            <el-button type="primary" @click="submitFormAdd()">保存并关闭</el-button>-->
                                <el-upload

                                        action=""
                                        :on-change="handleChange"
                                        :show-file-list="false"
                                        :auto-upload="false"
                                        style="float: left;">
                                    <el-button  type="primary"
                                                style="float: left; margin-right: 10px"
                                    >读取excel文件</el-button>
                                </el-upload>
                                <el-button style="float: left" type="success" @click="add">添加一行</el-button>
                                <el-button style="float: left" type="danger" @click="reduce" :disabled="flag">删除一行</el-button>
                                <el-button style="float: left;margin-left: 10px" type="warning" @click="resetForm()">重置</el-button>
                            </el-form-item>
                        </el-form>
                    </div>


<!--                <el-form-item label="备注" >-->
<!--                    <el-input v-model="form.remark" autocomplete="off"></el-input>-->
<!--                </el-form-item>-->

                <div style="margin: 10px 0; text-align: right">
                    <el-button  size="small" autocomplete="off" @click="dialogFormVisibl = false">取消</el-button>
                    <el-button type="primary" size="small" autocomplete="off" @click="edit">确定</el-button>
                </div>
            </el-form>

        </el-dialog>

    </div>

</template>

<script>

    export default {
        computed:{
            currentPathName(){
                //页面名称
                return this.$store.state.currentPathName;  //需要监听的数据
            }
        },
        data() {

            return {
                tableData: [],
                selectYaliniuju:[],
                multipleSelection:[],
                total:0,
                collapseBtnClass: 'el-icon-s-fold',
                isCollapse: false,
                sideWidth: 200,
                logoTextShow: true,
                headerBg: 'headerBg',
                pageNum:1,
                pageSize:10,
                name:'',
                name1:'',
                dialogFormVisible:false,
                dialogFormVisibl:false,
                dialogFormVisib:false,
                form:{},
                yid:'',
                id:'',
                teachers:[],
                rules: {
                    name: [
                        {required: true, message: '请输入型号', trigger: 'blur'},
                        {min: 1, max: 20, message: '长度在 310 个字符', trigger: 'blur'}
                    ],
                    category: [
                        {required: true, message: '请输入类别', trigger: 'blur'},

                    ],
                    tooth: [
                        {required: true, message: '请输入齿形', trigger: 'blur'},
                    ],
                    brand: [
                        {required: true, message: '请输入齿形', trigger: 'blur'},
                    ],
                    niuju: [
                        {required: true, message: '请输入扭矩压力', trigger: 'blur'},
                    ],
                    yali: [
                        {required: true, message: '请输入扭矩压力', trigger: 'blur'},
                    ],
                },
                // 表单
                ruleFormNL: [
                    {
                        id:'',
                        torque: '',
                        pressure: '',
                    }
                ],
                flag: true,
                fileContent: '',
                file: '',
                data: '',
                user:localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")):{},
                //操作日志
                operation:[],
                logDiaLogFrom:false,
                log: {
                    modified:'',
                    valueId:'',
                    toolValue: 'yybsvalue'
                },
                create: [
                    {
                        creator:'',
                        createTime:''
                    },
                ],
                //操作记录
                userlog:{
                    operatorRole:'',
                    operation:'',
                    surface:'',
                    fieldId:'',
                    userid:''
                }

            }
        },
        created(){
            this.load()
        },

        methods: {
            load(){
                this.request.get("/yybsvalue/page",{
                    params:{
                        pageNum: this.pageNum,
                        pageSize: this.pageSize,
                        name: this.name,
                    }
                })
                    .then(res => {
                        console.log(res.data)
                        this.tableData = res.data.records
                        this.total =res.data.total

                    })

            },
            //操作记录
            userLogFun(){
                this.userlog.operatorRole=this.user.nickname
                this.userlog.userid=this.user.id
                this.userlog.surface=this.currentPathName
                console.log(this.userlog)
                this.request.post("/cj-user-log/save",this.userlog).then(res=>{})
            },
           
            handAdd(){
                this.dialogFormVisible=true
                this.form={}
                this.ruleFormNL=[
                    {
                        id:'',
                        torque: '',
                        pressure: '',
                        category: ''
                    }
                ]
                this.flags()
            },
            handleEdit(row){

                this.flag=false
                this.request.get("/yvnjyl/findNjyl",{
                    params: {
                        name: row.name
                    }
                }).then(resq => {
                    this.selectYaliniuju=resq.data
                    console.log(this.selectYaliniuju)

                    this.ruleFormNL=this.selectYaliniuju
                    this.form=row
                    this.name1=this.form.name
                    this.form.njyl=this.selectYaliniuju
                    this.dialogFormVisibl=true
                    console.log(this.ruleFormNL)
                })

            },
            del(id,msg){
                if (msg<1){
                    this.request.post("/yybsvalue/del/"+id).then(res =>{
                        if (res.data){
                            this.$message.success("删除成功")
                            //操作记录
                            this.userlog.fieldId=id
                            this.userlog.operation='删除'
                            this.userLogFun()
                            this.load()
                        }else {
                            this.$message.error("删除失败")
                        }
                    })
                }else {
                    this.$message.error("存在扳手,禁止删除")

                }

            },
            handleSelectionChange(val){
                console.log(val)
                this.multipleSelection = val
            },
            reset(){
                this.name=""
                this.load()
            },
            save(){
                // console.log(this.ruleFormNL)
                let judge=0;
                for(var i=0;i<this.ruleFormNL.length;i++){
                    if (this.ruleFormNL[i].pressure=="" || this.ruleFormNL[i].pressure==null){
                        judge=1
                    }
                    if (this.ruleFormNL[i].torque=="" || this.ruleFormNL[i].torque==null){
                        judge=1;
                    }
                }
                if (judge==0){
                    this.$refs['addForm'].validate((valid1) => {
                        if (valid1) {//表单验证
                            this.form.createBy=this.user.nickname
                            this.request.post("/yybsvalue/save", this.form).then(res => {

                                if (res.data) {
                                    this.submitFormAdd()
                                    this.$message.success("保存成功")
                                    this.dialogFormVisible = false
                                    //操作记录
                                    this.request.get("/yybsvalue/findId/"+this.form.name).then(res1 => {
                                        this.userlog.fieldId=res1.data.id
                                        this.userlog.operation='添加'
                                        this.userLogFun()
                                    })
                                    this.load()
                                }else if (res.data==0){
                                    this.$message.error("型号已存在")
                                }else {
                                    this.$message.error("失败")
                                }
                            })
                        } else {
                            return false;
                        }
                    });
                }else {
                    this.$message.error("扭矩或压力不能为空")
                }

            },
            edit(){
                // console.log(this.form.msg)
                let judge=0;
                for(var i=0;i<this.ruleFormNL.length;i++){
                    if (this.ruleFormNL[i].pressure=="" || this.ruleFormNL[i].pressure==null){
                        judge=1
                    }
                    if (this.ruleFormNL[i].torque=="" || this.ruleFormNL[i].torque==null){
                        judge=1;
                    }
                }
                if (judge==0){
                    if (this.form.msg <1){
                        if(this.$refs['editForm'] !== undefined) {
                            this.$refs['editForm'].validate((valid) => {
                                if (valid) {//表单验证
                                    if (this.name1==this.form.name){
                                        this.request.post("/yybsvalue/edit",this.form).then(res => {

                                            if (res.data){
                                                this.submitFormEdit()
                                                this.$message.success("保存成功")
                                                this.dialogFormVisibl=false
                                                this.log.modified=this.user.nickname
                                                this.log.valueId=this.form.id
                                                this.request.post("/tool-log/add",this.log).then(ress =>{
                                                })
                                                //操作记录
                                                this.userlog.fieldId=this.form.id
                                                this.userlog.operation='修改'
                                                this.userLogFun()
                                                this.load()
                                                // console.log(judge)
                                            }else if (res.data==0){
                                                this.$message.error("型号已存在")
                                                this.load()
                                            }else {
                                                this.$message.error("失败")
                                            }
                                        })
                                    }else {
                                        this.request.post("/yybsvalue/save",this.form).then(res => {

                                            if (res.data){
                                                this.submitFormEdit()
                                                this.$message.success("保存成功")
                                                this.dialogFormVisibl=false
                                                this.log.modified=this.user.nickname
                                                this.log.valueId=this.form.id
                                                this.request.post("/tool-log/add",this.log).then(ress =>{
                                                })
                                                //操作记录
                                                this.userlog.fieldId=this.form.id
                                                this.userlog.operation='修改'
                                                this.userLogFun()
                                                this.load()
                                            }else if (res.data==0){
                                                this.$message.error("型号已存在")
                                                this.load()
                                            }else {
                                                this.$message.error("失败")
                                            }
                                        })
                                    }

                                } else {
                                    return false;
                                }
                            });
                        }
                    }else {
                        this.$message.error("型号下有扳手,无法更改")
                    }
                }else {
                    this.$message.error("扭矩或压力不能为空")
                }
            },
            handleSizeChange(pageSize) {
                this.pageSize=pageSize
                this.load()
            },
            handleCurrentChange(pageNum) {
                this.pageNum=pageNum
                this.load()
            },
            submitFormAdd(){
                console.log("21dwfdfs")
                console.log(this.ruleFormNL)
                for (var i=0 ; i< this.ruleFormNL.length;i++){
                    this.ruleFormNL[i].category=this.form.name
                    this.ruleFormNL[i].id=''
                }

                console.log(this.ruleFormNL)
                this.request.post("/yvnjyl/saveBath",this.ruleFormNL).then(res  =>{
                    if (res.data){
                        this.dialogFormVisible=false
                        this.load()
                    }else {
                        this.$message.error("扭矩压力保存失败")
                    }

                })
            },
            submitFormEdit(){
                 console.log(this.ruleFormNL)
                for (var i=0 ; i< this.ruleFormNL.length;i++){
                    this.ruleFormNL[i].category=this.form.name
                    this.ruleFormNL[i].id=''
                }
                // console.log(this.ruleFormNL)
                this.request.post("/yvnjyl/delCategory/"+this.form.name).then(res=>{
                    console.log("删除成功")
                })
                this.request.post("/yvnjyl/saveOrUpdateBatc",this.ruleFormNL).then(res  =>{
                    if (res.data){
                        this.dialogFormVisible=false
                        this.load()
                    }else {
                        this.$message.error("失败")
                    }
                })
            },
            //删除表单内的一行
            reduceNj(id){
                console.log(id)
                let id1 = this.ruleFormNL.findIndex(item => {
                    if (item.id == id) {
                        return true
                    }
                })
                this.ruleFormNL.splice(id1, 1)
                this.flags()
            },
            // 表单添加一行
            add() {
                var arr = {torque: '', pressure: '', category: ''}
                this.ruleFormNL.push(arr)
                this.flags()
            },
            // 表单减少一行
            reduce() {

                this.ruleFormNL.length = this.ruleFormNL.length - 1
                this.flags()
            },
            // 判断数组长度
            flags() {
                console.log(this.ruleFormNL.length)
                for (var i=0;i<this.ruleFormNL.length;i++){
                    this.ruleFormNL[i].id=i+1
                }
                if (this.ruleFormNL.length < 1) {
                    this.flag = true

                } else {
                    //先赋值为true再赋为false, 不然会没反应
                    this.flag = true
                    this.flag = false
                }
            },
            // 重置方法
            resetForm() {
                this.ruleFormNL = [{}]
            },
// 核心部分代码(handleChange 和 importfile)
            handleChange(file) {
                console.log(file);
                this.fileContent = file.raw
                const fileName = file.name
                const fileType = fileName.substring(fileName.lastIndexOf('.') + 1)
                if (this.fileContent) {

                    if (fileType === 'xlsx' || fileType === 'xls') {

                        this.importfile(this.fileContent)
                    } else {

                        this.$message({

                            type: 'warning',
                            message: '附件格式错误,请重新上传!'
                        })
                    }
                } else {

                    this.$message({

                        type: 'warning',
                        message: '请上传附件!'
                    })
                }
            },
            importfile(obj) {
                console.log(obj);
                const reader = new FileReader()
                const _this = this
                reader.readAsArrayBuffer(obj)
                reader.onload = function () {

                    const buffer = reader.result
                    const bytes = new Uint8Array(buffer)
                    const length = bytes.byteLength
                    let binary = ''
                    for (let i = 0; i < length; i++) {

                        binary += String.fromCharCode(bytes[i])
                    }
                    const XLSX = require('xlsx')
                    const wb = XLSX.read(binary, {

                        type: 'binary'
                    })
                    const outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])
                    this.data = [...outdata]
                    const arr = []
                    this.data.map(v => {

                        const obj = {}

                        obj.pressure = v.压力
                        obj.torque = v.扭矩
                        obj.category = v.category
                        console.log(obj);
                        arr.push(obj)
                    })
                    _this.ruleFormNL = _this.ruleFormNL.concat(arr)
                }
            },

        }
    };
</script>

<style>
    .el-header {
        border: 1px solid #eee;
        line-height: 60px;
    }

    .el-aside {
        color: #333;
    }

    .headerBg {
        background: lightblue !important;
    }
</style>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值