element ui el-form 表单错误 滚动可视区域

  /**
     * 表单提交处理
     */
    handleSubmit() {
      // 调用 el-form 验证方法
      this.$refs.myForm.validate((valid, errorFields) => {
        if (valid) {
          // 验证通过,执行提交逻辑
          this.$message.success("表单验证通过,即将提交");
          // TODO: 接口请求提交数据
        } else {
          // 验证失败,滚动到第一个错误项
          this.scrollToFirstError(errorFields);
          this.$message.error("表单验证失败,请检查必填项");
        }
      });
    }

 

滚动错误区域

  /**
     * 滚动到第一个验证错误项
     * @param {Array} errorFields - 验证失败的字段数组(el-form validate 回调返回)
     */
    scrollToFirstError(errorFields) {
      const _errorFields = Object.keys(errorFields) || [];
      if (!_errorFields || _errorFields.length === 0) return;

      // 1. 获取第一个错误字段的 prop
      const firstErrorProp = _errorFields[0];

      // 2. 根据 prop 找到对应的 el-form-item 元素(通过属性选择器)
      const firstErrorItem = document.querySelector(
        `.demo-form [for="${firstErrorProp}"]`
      );

      if (firstErrorItem) {
        // 3. 滚动到错误项可视区域(behavior: 'smooth' 平滑滚动,block: 'center' 居中显示)
        firstErrorItem.scrollIntoView({
          behavior: "smooth", // 平滑滚动(可选:auto 立即滚动)
          block: "center", // 垂直方向居中(可选:start 顶部对齐,end 底部对齐)
          inline: "nearest", // 水平方向不滚动
        });

        // 可选:给错误项添加高亮样式(增强视觉提示)
        this.highlightErrorItem(firstErrorItem);
      }
    },

    /**
     * 错误项高亮提示(可选)
     * @param {Element} errorItem - 错误项 DOM 元素
     */
    highlightErrorItem(errorItem) {
      // 添加高亮样式
      errorItem.style.boxShadow = "0 0 8px rgba(245, 108, 108, 0.5)";
      errorItem.style.borderRadius = "4px";
      // 3秒后移除高亮
      setTimeout(() => {
        errorItem.style.boxShadow = "";
      }, 3000);
    },

 

posted on 2025-12-25 14:19  Mc525  阅读(3)  评论(0)    收藏  举报

导航