Vue表单校验失败滚动到错误位置

表单校验失败之后都会有一个class属性.is-error的类名,可以查找到目前第一个错误元素所对应的视图区域,进行定位,验证未通过的表单提示
scrollIntoView介绍https://docs.microsoft.com/zh-cn/office/vba/api/excel.window.scrollintoview

.main.js

Vue.prototype.$errorScroll = function errorScroll(callback){
  this.$nextTick(() => {
    this.loading = false;
    let isError = document.getElementsByClassName('is-error')
    this.$api.error(isError[0].innerText);
    isError[0].scrollIntoView({
        // 滚动到指定节点
        block: 'center',
        behavior: 'smooth',
    })
    if(callback){
      if(typeof callback !== 'function'){
        throw new TypeError(callback + 'is not a function');
      } else {
        callback();
      }
    }
  })
}

this.$refs['form'].validate((valid) => {
...
} else {
// 校验失败调用
this.$errorScroll(); // 调用挂载的方法
}

愿以往所学皆有所获
原文地址:https://www.cnblogs.com/Azune/p/14583692.html