Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

element ui的表单校验怎么循环校验?

场景:开发微信自定义菜单的功能,每个菜单的编辑是使用的同样的表单,菜单切换时候会更新表单数据,在点击保存菜单按钮的时候应该先循环校验菜单数组,校验成功后再调用保存菜单接口。

问题:因为每个菜单的编辑都是用的同一个表单,但是element的form表单校验是通过获取当前form的ref调用validate来校验的,也就是只能校验当前的菜单数据。

因为微信菜单是个数组,怎么用element循环校验整个菜单数组呢?不会需要循环这个数组,把每项的数据都赋值到form表单上一遍每次调用validate来校验吧。而且validate校验还是异步的?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<el-form-item label="联系人:" prop="trailer.address.name" ref="trailer.address.name">
            <el-input v-model="form.trailer.address.name" placeholder="请输入工厂联系人"></el-input>
          </el-form-item>
          <el-form-item label="手机号码:" prop="trailer.address.phone" ref="trailer.address.phone">
            <el-input v-model="form.trailer.address.phone" placeholder="请输入手机号码"></el-input>
          </el-form-item>
          <el-form-item label="so号:" prop="trailer.so_no" ref="trailer.so_no">
            <el-input v-model="form.trailer.so_no"></el-input>
      </el-form-item>
this.$refs[formName].validate((valid, object) => {
          console.log(object)  //object就是未通过校验的字段
          if (valid) {
            //验证通过
          } else {        for (let i in object) {
              let dom = this.$refs[i];            
              if (Object.prototype.toString.call(dom) !== '[object Object]') {  
                //这里是针对遍历的情况(多个输入框),取值为数组
                dom = dom[0];
              }                          
            //第一种方法(包含动画效果)
              dom.$el.scrollIntoView({  //滚动到指定节点
                block: 'center',     //值有start,center,end,nearest,当前显示在视图区域中间
                behavior: 'smooth'    //值有auto、instant,smooth,缓动动画(当前是慢速的)
              })
        //第二种方法
              let top = dom.$el.getBoundingClientRect().top;  //获取当前节点的偏移值
              let scrollTop = document.documentElement.scrollTop;  //获取视图滚动值
              let diff = top + scrollTop;
  
              document.documentElement.scrollTop = diff - 276;  //276是第一个输入框节点距离顶部的偏移值,也可以在初始化提前保存
              //window.scrollTo(0,diff- 276) //同上
              break; //因为我们只需要检测一项,所以就可以跳出循环了
            }
          }
        });

这是我项目中使用的方法,你可以作为参考~


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...