一、scrollView.js
function scrollView(object) {
for (const i in object) {
let dom = this.$refs[i]
// 这里是针对遍历的情况(多个输入框),取值为数组
if (Object.prototype.toString.call(dom) !== '[object Object]') {
dom = dom[0]
}
// 第一种方法(包含动画效果)
dom.$el.scrollIntoView({
// 滚动到指定节点
// 值有start,center,end,nearest,当前显示在视图区域中间
block: 'center',
// 值有auto、instant,smooth,缓动动画(当前是慢速的)
behavior: 'smooth'
})
break // 跳出循环了
}
}
export default scrollView
二、在main.js里挂载使用,可全局使用
import scrollView from '@/utils/scrollView.js'
Vue.prototype.$scrollView = scrollView
三、使用
save() {
this.$refs['detailForm'].validate((valid, val) => {
if (valid) {
// 验证通过后的操作
} else {
this.$scrollView(val)
return false
}
})
}
四、注意
表单项必须加上ref,且ref与该表单项的prop的值须保持一致。