在main.js中定义全局方法
Vue.prototype.$errorScroll = function errorScroll(dom){
this.$nextTick(() => {
let isError = document.getElementsByClassName('ivu-form-item-error')
document
.querySelector(dom)
.scrollTo({ behavior: 'smooth', top: heightToTop(isError[0]) - 40 - 100 })
}, 500)
}
function heightToTop (ele) {
//ele为指定跳转到该位置的DOM节点
let root = document.body
let height = 0
do {
height += ele.offsetTop
ele = ele.offsetParent
} while (ele !== root)
return height
}
然后在表单验证失败之后调用此方法即可
this.$refs.main.validate(valid => {
if (valid) {
return this.newForm;
} else {
this.$errorScroll('.apply-content');
}
});