vue form validation (c)
Every time I see heyui this form validation, I always wanted to do the verification element of a similar function, finally have the way, although not perfect, but it can be used to meet the requirements of the
Implementation based on element-ui
realization
When you submit through a form, to trigger the check, not by the form will be added is-error
, after rolling to a position corresponding to an error
Page View
Implementation logic
- Triggering conditions
At the time of submission, if not to start by the judge, because it is dependent on the is-error
class name of the class, thus requiring the wrong element and so form a form finished adding is-error
the class name before judge
submitForm1 () {
this.$refs['ruleForm'].validate(valid => {
if (valid) {
// 通过
} else {
// 需要延迟一下
this.$nextTick(() => {
this.scrollToTop(this.$refs['ruleForm'].$el)
})
}
})
}
js logic
scrollToTop (node) {
const ChildHasError = Array.from(node.querySelectorAll('.is-error'))
if (!ChildHasError.length) throw new Error('有错误,但是找不到错误位置')
// 找到第一个错误位置
const FirstErrorNode = ChildHasError[0]
// https://www.zhangxinxu.com/wordpress/2018/10/scroll-behavior-scrollintoview-%E5%B9%B3%E6%BB%91%E6%BB%9A%E5%8A%A8/
FirstErrorNode.scrollIntoView({
behavior: "smooth"
})
}
With the above scrollIntoView
, but there is a small problem, form a form error messages are close to the top, not very consistent, and thus began to write their own rolling
upgrade
Scroll Animation
const BackToTop = (rate = 2, num = 0) => {
const doc = document.body.scrollTop ? document.body : document.documentElement
// 距离顶部的值
let scrollTop = doc.scrollTop
const top = function () {
scrollTop = scrollTop + (num - scrollTop) / (rate || 2);
// 临界判断,终止动画
if (scrollTop < (num + 1)) {
doc.scrollTop = num;
return;
}
doc.scrollTop = scrollTop;
// 动画gogogo!
requestAnimationFrame(top);
};
top();
}
js logical upgrade
scrollToTop (node) {
const ChildHasError = Array.from(node.querySelectorAll('.is-error'))
if (!ChildHasError.length) throw new Error('有错误,但是找不到错误位置')
const FirstErrorNode = ChildHasError[0]
const Top = FirstErrorNode.getBoundingClientRect().top
// 获取元素相对于页面顶部的位置, 同时设置相对40px
const scrollToTop = Top + ( window.pageYOffset || document.documentElement.scrollTop ) - ( document.documentElement.clientTop || 0 ) - 40
scrollTop(2, scrollToTop)
}
[FIG Effect]] ( https://img2018.cnblogs.com/blog/1363709/201907/1363709-20190701100826762-238379584.gif )
to sum up
- More is to consider how to achieve a rolling effect
- There are further required, if the use of the
el-scroll
components, and then continue to change the way you win, then the post-finishing