Element-plus 表单校验未通过时,页面滚动到未通过的位置。
表单项目校验未通过时,项目会自动添加is-error
属性。
可以借助这个属性获取错误项目位置,然后使用scrollIntoView()
滚动页面。
scrollIntoView()
方法,参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView
scrollIntoViewOptions (可选) 一个包含下列属性的对象:
behavior(可选),定义滚动是立即的还是平滑的动画。该选项是一个字符串,必须采用以下值之一:
- smooth:滚动应该是平滑的动画。
- instant:滚动应该通过一次跳跃立刻发生。
- auto:滚动行为由 scroll-behavior 的计算值决定。
block,定义垂直方向的对齐,start、center、end 或 nearest 之一。默认为 start。
inline(可选),定义水平方向的对齐,start、center、end 或 nearest 之一。默认为 nearest。
import { nextTick } from 'vue';
await nextTick();
const isError = document.getElementsByClassName('is-error');
if (isError[0]) {
isError[0].scrollIntoView({
behavior: 'smooth',
block: 'center',
});
}