Vue elementUI表单嵌套表格并对每行进行校验详解


Posted in Vue.js onFebruary 18, 2022

效果展示

先看看这是不是需要的效果^_^

Vue elementUI表单嵌套表格并对每行进行校验详解

如图,ElementUI 表单里嵌套了表格,表格内每行能进行【保存】【新增】【编辑】【删除】【重置】等操作,同时可以对每行的某些字段进行校验(而不是整个表单校验!),这种需求很常见,所以记录下来。

代码链接

gitee地址

关键代码

表格数据

// 数据格式必须是【对象嵌套数组】,【form】绑定表单,【list】绑定表格
form: {
  // 表格数据
  list: [
      { id: 1, name: '小叶', age: '12', phone: '123456', show: true },
      { id: 2, name: '小李', age: '23', phone: '123457', show: true },
      { id: 3, name: '小林', age: '12', phone: '123458', show: true }
  ]
},

组件嵌套

  1. 添加字段校验的时候,格式必须写成这样的 :prop="'list.' + scope.$index + '.name'"
    这是 elementui 规定的格式,渲染后的结果为 list.1.name
  2. 每个字段要动态绑定表单的 rules 属性
  3. 如果不是以上的格式,会出错!!!
// 表单必须嵌套在表格的外面,表单必须绑定【rules】【ref】属性
<el-form :model="form" :rules="rules" ref="form">
   <el-table :data="form.list">
       <el-table-column prop="name" label="姓名">
           <template scope="scope">
              // 每个字段动态的绑定表单的【prop】【rules】属性
              <el-form-item :prop="'list.' + scope.$index + '.name'"                                              :rules="rules.name">
                    <el-input size="mini" v-model="scope.row.name" placeholder="请输入"                             clearable></el-input>
               </el-form-item>
           </template>
       </el-table-column>
  </el-table>
</el-form>

校验方法

  1. 表单的字段对象存在于 this.$refs['form'].fields 中,并且字段对象具有 prop【datas.1.name】 属性和 validateField 方法【验证 datas.1.name 能否通过校验】
  2. 但是 validateField 方法需要手动创建来验证能否通过校验
  3. 必须创建,否则会出错!!!
// 表单校验方法
// 【form】是需要校验的表单,就是表单中【ref】绑定的字段
// 【index】是需要传入的行数,字段【scope.$index】
validateField(form, index) {
     let result = true;
     for (let item of this.$refs[form].fields) {
         if(item.prop.split(".")[1] == index){
             this.$refs[form].validateField(item.prop, err => {
                 if(err !="") {
                     result = false;
                 }
             });
         }
         if(!result) break;
     }
     return result;
}

重置方法

// 对【需要校验】的表单字段进行重置
// 参数同校验方法,如果是全部重置
reset(form, index) {
    this.$refs[form].fields.forEach(item => {
        if(item.prop.split(".")[1] == index){
            item.resetField();
        }
    })
}
// 如果需要全部重置可以直接质控表单中字段
// 【row】是每行传入的数据
resetRow(row) {
    row.name = "";
    row.age = "";
    row.phone = "";
}

完整代码

因为用的是在线链接,网络不稳定时页面不一定能加载出来,使用时可以更换成本地的!

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>vue表单嵌套表格逐行验证</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css" rel="external nofollow" >
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>

<body>
    <div id="app">
        <!-- 页面组件 -->
        <h2 style="text-align: center; line-height: 23px;color: #909399;">vue表单嵌套表格逐行验证</h2>
        <el-form :model="form" :rules="rules" ref="form" :inline="true"
            style="margin: 23px auto 0px; width: 96%; overflow: hidden;">
            <el-table border :data="form.list">
                <el-table-column align="center" prop="id" label="序号" width="55">
                </el-table-column>
                <el-table-column align="center" prop="name" label="姓名">
                    <template scope="scope">
                        <el-form-item :prop="'list.' + scope.$index + '.name'" :rules="rules.name"
                            v-if="scope.row.show">
                            <el-input size="mini" v-model="scope.row.name" placeholder="请输入" clearable>
                            </el-input>
                        </el-form-item>
                        <div v-if="!scope.row.show">{{scope.row.name}}</div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="age" label="年龄">
                    <template scope="scope">
                        <el-form-item :prop="'list.' + scope.$index + '.age'" :rules="rules.age" v-if="scope.row.show">
                            <el-input size="mini" v-model="scope.row.age" placeholder="请输入" clearable>
                            </el-input>
                        </el-form-item>
                        <div v-if="!scope.row.show">{{scope.row.age}}</div>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="phone" label="联系方式">
                    <template scope="scope">
                        <el-form-item :prop="'list.' + scope.$index + '.phone'" :rules="rules.phone"
                            v-if="scope.row.show">
                            <!-- <el-form-item v-if="scope.row.show"> -->
                            <el-input size="mini" v-model="scope.row.phone" placeholder="请输入" clearable>
                            </el-input>
                        </el-form-item>
                        <div v-if="!scope.row.show">{{scope.row.phone}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="290" fixed="right">
                    <template slot-scope="scope">
                        <el-button type="text" style="color: #E6A23C;" @click="save(scope.$index, scope.row)"
                            v-if="scope.row.show" icon="el-icon-check">保存
                        </el-button>
                        <el-button type="text" style="color: #409EFF;" @click="edit(scope.row)" v-if="!scope.row.show"
                            icon="el-icon-edit">编辑
                        </el-button>
                        <el-button type="text" style="color: #67C23A;" v-if="scope.$index+1 == listLength"
                            @click="addRow(scope.$index, scope.row)" icon="el-icon-plus">新增
                        </el-button>
                        <el-button type="text" style="color: #F56C6C;" @click="delRow(scope.$index, scope.row)"
                            icon="el-icon-delete">删除
                        </el-button>
                        <el-button type="text" style="color: #909399;" @click="reset('form', scope.$index)"
                            v-if="scope.row.show" icon="el-icon-refresh">重置
                        </el-button>
                        <!-- <el-button type="text" style="color: #909399;" @click="resetRow(scope.row)"
                            v-if="scope.row.show" icon="el-icon-refresh">重置
                        </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </el-form>
    </div>
</body>

</html>
<script>
    var app = new Vue({
        el: '#app',
        data() {
            return {
                // 表单数据
                form: {
                    // 表格数据
                    list: [{ id: 1, name: '', age: '', phone: '', show: true }]
                },
                // 表单验证规则
                rules: {
                    name: [{ required: true, message: '请输入姓名!', trigger: 'blur' }],
                    age: [{ required: true, message: '请输入年龄!', trigger: 'blur' }],
                    phone: [{ required: true, message: '请输入联系方式!', trigger: 'blur' }],
                },
                // 表格长度默认为 1
                listLength: 1,
            }
        },

        methods: {
            // 校验
            validateField(form, index) {
                let result = true;
                for (let item of this.$refs[form].fields) {
                    if (item.prop.split(".")[1] == index) {
                        this.$refs[form].validateField(item.prop, err => {
                            if (err != "") {
                                result = false;
                            }
                        });
                    }
                    if (!result) break;
                }
                return result;
            },

            // 重置【只针对校验字段】
            reset(form, index) {
                this.$refs[form].fields.forEach(item => {
                    if (item.prop.split(".")[1] == index) {
                        item.resetField();
                    }
                })
            },

            // 重置【全部】
            resetRow(row) {
                row.name = "";
                row.age = "";
                row.phone = "";
            },

            // 保存
            save(index, row) {
                if (!this.validateField('form', index)) return;
                row.show = false;
            },

            // 新增
            addRow(index, row) {
                if (!this.validateField('form', index)) return;
                this.form.list.push({
                    id: index + 2,
                    name: '',
                    age: '',
                    phone: '',
                    show: true
                });
                this.listLength = this.form.list.length;
            },

            // 编辑
            edit(row) {
                row.show = true;
            },

            // 删除
            delRow(index, row) {
                if (this.form.list.length > 1) {
                    this.form.list.splice(index, 1);
                    this.listLength = this.form.list.length;
                } else {
                    this.form.list = [{
                        id: 1,
                        name: '',
                        age: '',
                        phone: '',
                        show: true
                    }];
                }
            },
        }
    })
</script>

总结

到此这篇关于Vue elementUI表单嵌套表格并对每行进行校验的文章就介绍到这了,更多相关elementUI表单嵌套表格内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Vue.js 相关文章推荐
vue+element UI实现树形表格
Dec 29 Vue.js
基于vuex实现购物车功能
Jan 10 Vue.js
vue二选一tab栏切换新做法实现
Jan 19 Vue.js
vue form表单post请求结合Servlet实现文件上传功能
Jan 22 Vue.js
vue如何使用rem适配
Feb 06 Vue.js
开发一个封装iframe的vue组件
Mar 29 Vue.js
关于vue中如何监听数组变化
Apr 28 Vue.js
vue组件的路由高亮问题解决方法
May 11 Vue.js
vue-element-admin项目导入和导出的实现
May 21 Vue.js
vite+vue3.0+ts+element-plus快速搭建项目的实现
Jun 24 Vue.js
简单聊聊Vue中的计算属性和属性侦听
Oct 05 Vue.js
Vue监视数据的原理详解
Feb 24 Vue.js
vue项目支付功能代码详解
Feb 18 #Vue.js
Vue自定义铃声提示音组件的实现
Jan 22 #Vue.js
Vue提供的三种调试方式你知道吗
Jan 18 #Vue.js
详解Vue项目的打包方式(生成dist文件)
Jan 18 #Vue.js
Element-ui Layout布局(Row和Col组件)的实现
Dec 06 #Vue.js
详解gantt甘特图可拖拽、编辑(vue、react都可用 highcharts)
Nov 27 #Vue.js
Vue实现跑马灯样式文字横向滚动
Nov 23 #Vue.js
You might like
ThinkPHP 防止表单重复提交的方法
2011/08/08 PHP
解析centos中Apache、php、mysql 默认安装路径
2013/06/25 PHP
学习YUI.Ext第五日--做拖放Darg&amp;Drop
2007/03/10 Javascript
javascript 写类方式之七
2009/07/05 Javascript
JQuery 解析多维的Json数据格式
2009/11/02 Javascript
jQuery '行 4954 错误: 不支持该属性或方法' 的问题解决方法
2011/01/19 Javascript
用javascript模仿ie的自动完成类似自动完成功的表单
2012/12/12 Javascript
jquery自动将form表单封装成json的具体实现
2014/03/17 Javascript
深入理解Java线程编程中的阻塞队列容器
2015/12/07 Javascript
神奇!js+CSS+DIV实现文字颜色渐变效果
2016/03/16 Javascript
JS构造函数与原型prototype的区别介绍
2016/07/04 Javascript
javascript超过容器后显示省略号效果的方法(兼容一行或者多行)
2016/07/14 Javascript
详解Vue 方法与事件处理器
2017/06/20 Javascript
如何重置vue打印变量的显示方式
2017/12/06 Javascript
d3.js实现图形拖拽
2019/12/19 Javascript
javascript实现贪吃蛇小练习
2020/07/05 Javascript
[04:03]辉夜杯主赛事 12月25日RECAP精彩回顾
2015/12/26 DOTA
Nginx搭建HTTPS服务器和强制使用HTTPS访问的方法
2015/08/16 Python
python在Windows下安装setuptools(easy_install工具)步骤详解
2016/07/01 Python
python 将md5转为16字节的方法
2018/05/29 Python
python3.6利用pyinstall打包py为exe的操作实例
2018/10/31 Python
利用Python将数值型特征进行离散化操作的方法
2018/11/06 Python
Django REST framework 分页的实现代码
2019/06/19 Python
使用APScheduler3.0.1 实现定时任务的方法
2019/07/22 Python
django queryset相加和筛选教程
2020/05/18 Python
python 如何快速复制序列
2020/09/07 Python
Html5基于canvas实现电子签名并生成PDF文档
2020/12/07 HTML / CSS
UNDONE手表官网:世界领先的定制手表品牌
2018/11/13 全球购物
Juicy Couture Beauty官方网站:香水和化妆品
2019/03/12 全球购物
J2EE是技术还是平台还是框架
2016/08/14 面试题
2014道德模范事迹材料
2014/02/16 职场文书
铁路安全反思材料
2014/12/24 职场文书
离婚起诉书范本
2015/05/18 职场文书
高一英语教学反思
2016/03/03 职场文书
Python源码解析之List
2021/05/21 Python
Python3.8官网文档之类的基础语法阅读
2021/09/04 Python