写在后面:如果您认为我这个实现计划简洁好用,请点赞、评论加珍藏,感激!如果发现这个计划还有欠缺或谬误的中央欢送评论斧正。如果您有更好的计划也欢送评论分享

待解决的问题/需要

业务里呈现长表单提交时,用户/业务方/产品经理常常会提的一个需要就是表单校验失败你应该给我滚动定位到对应的谬误地位,不便我晓得哪里呈现了谬误。也是晋升填写长表单时的用户体验一个很常见的做法。

解决方案

utils/index.js

// el-form校验失败滚动到对应的谬误地位export function elFormErrorScrollIntoView() {  // 获取第一个校验谬误的元素  const element = document.querySelectorAll('.el-form-item__error')[0]  // 滚动到谬误元素对应地位  element.scrollIntoView({    behavior: 'smooth',    block: 'center'  })}

form.vue

<template>    <el-form ref="form" :model="form" :rules="rules">        ...    </el-form>    <el-button @click="submitForm">提交</el-button></template><script>    import { elFormErrorScrollIntoView } from '@/utils'        export default {        data() {            return {                form: { ... },                rules: { ... }            }        },        method: {            submitForm() {                this.$refs.form.validate((valid) => {                    if (valid) {                        // 数据校验胜利                        ...                    } else {                        // 数据校验失败                        // 应用$nextTick的起因是,谬误提醒的元素是在视图更新后呈现的,不应用$nextTick获取元素是undefined                        this.$nextTick(() => {                            elFormErrorScrollIntoView()                        })                    }                })            }        }    }</script>

知识点、参考文档

document.querySelectAll

参考文档:https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Element.scrollIntoView()

参考文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

兼容性

参考文档:https://caniuse.com/?search=s...
支持率十分好,能够放心使用,很多局部反对仅仅只是不反对smooth参数