vue + iview表单提交自动定位(滚动)到错误的地方

198 阅读1分钟

代码

this.$nextTick(()=>{
    const errorElement = document.getElementsByClassName('ivu-form-item-error');
    const parent = document.querySelector('.myForm');
    // const parent = this.$refs.myForm.$el;
    if(errorElement && errorElement[0] && parent){
        parent.scrollTo({
          top: errorElement[0].offsetTop-100,
          behavior: "smooth"
        });
    };
})

大致方案

1、找到错误的表单

iview会给校验不通过的表单添加类ivu-form-item-error,以此可以获取所有错误表单元素

2、使表单容器可滚动

通过overflow:auto/scroll;让表单容器可滚动,以便让容器滚动到错误表单的位置

3、获取错误表单到表单容器的相对位置

给表单容器设置一个position:relative;,用来错误表单通过offsetTop获取到表单容器的相对位置;

offsetTop:元素到offsetParent顶部的距离。

offsetParent:距离元素最近的一个具有定位(position:relative/absolute/fixed;)的祖宗元素,若祖宗都不符合条件,offsetParent为body。

注意:一般会使用Row/Col排版表单,iview默认给row与col设置了position:relative;,所以使用row/col后,offsetTop获取的就是错误表单到row/col的相对高度;所以要重置row/col的定位样式;

.ivu-row{
  position: static !important;
  .ivu-col{
    position: static !important;
  }
}

3、获取表单容器

一般是通过给表单设置calss或id获取到,例如class="myForm"id="myForm",然后通过document.querySelector('.myForm');获取表单容器;

注意: 如果你的表单定义成组件,在页面中多次引用,页面中也就有多个myForm表单,这时你通过class或id获取的表单就是错误的。

出现这种情况的话,可以给表单容器设置ref="myForm",通过this.$refs.myForm.$el获取到表单容器,即使有多个ref,在当前组件内也只能获取到当前这个表单的ref;

4、滚动到错误表单的位置

parent.scrollTo({
  top: errorElement[0].offsetTop-100,
  behavior: "smooth"
});

behavior: "smooth"表示平滑的滚动