You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中Bootstrap Modal重置及模态框嵌套卡顿问题求助

问题1:Bootstrap模态框关闭/提交后输入字段未重置

问题描述

Vue应用中使用Bootstrap Modal,模态框内的输入字段在提交数据并关闭模态框后,重新打开时仍保留之前的内容,需要实现提交或关闭模态框时重置所有输入字段。

解决方案

1. 定义表单重置方法

在Vue组件脚本中,创建重置方法将formData恢复到初始状态:

// 定义表单初始状态
const initialFormData = {
  hospital_id: '',
  machine_id: '',
  serialNo: ''
};

export default {
  data() {
    return {
      formData: {...initialFormData},
      formProcessing: false
    };
  },
  methods: {
    resetForm() {
      // 重置表单数据
      this.formData = {...initialFormData};
      // 若有表单验证状态,可在此同步重置
    },
    async saveSolution() {
      this.formProcessing = true;
      try {
        // 执行数据提交逻辑
        // ...
        // 提交成功后重置表单并关闭模态框
        this.resetForm();
        const modal = bootstrap.Modal.getInstance(document.getElementById('add_issue_solution_modal'));
        modal.hide();
      } catch (error) {
        // 错误处理逻辑
      } finally {
        this.formProcessing = false;
      }
    }
  },
  mounted() {
    // 监听模态框隐藏事件,关闭时自动重置表单
    const modal = document.getElementById('add_issue_solution_modal');
    modal.addEventListener('hidden.bs.modal', () => {
      this.resetForm();
    });
  }
};

2. 修正关闭按钮的表单关联

原代码中关闭按钮的form属性与实际表单ID不匹配,需修正:

<button type="reset" form="frm-update" class="btn btn-default btnCloseModal" data-bs-dismiss="modal">
  {{ Lang.get('Close') }}
</button>

问题2:模态框跳转后应用冻结、无法滚动

问题描述

打开一个模态框后,点击其中按钮打开另一个模态框时,应用冻结,无法在新模态框内滚动。

解决方案

问题根源

原代码存在两个核心问题:

  • 错误的类名判断逻辑(Bootstrap模态框隐藏时不会添加hidden类)
  • 前一个模态框的背景层未完全移除时就打开新模态框,导致body的overflow属性被多次锁定

正确实现方式

使用Bootstrap官方Modal实例API切换模态框,确保前一个模态框完全隐藏后再打开新模态框:

mounted() {
  // 获取两个模态框的官方实例
  const assignModal = new bootstrap.Modal(document.getElementById('assign_obsolescence_detail_issues_modal'));
  const getModal = new bootstrap.Modal(document.getElementById('get_detail_issues_modal'));

  // 监听第一个模态框的隐藏完成事件
  assignModal._element.addEventListener('hidden.bs.modal', () => {
    // 直接打开第二个模态框
    getModal.show();
  });
}

Vue组件内优化(推荐)

若使用自定义AppModal组件,通过ref获取元素避免原生DOM操作:

<template>
  <AppModal ref="assignModal" id="assign_obsolescence_detail_issues_modal">
    <!-- 模态框内容 -->
  </AppModal>

  <AppModal ref="getModal" id="get_detail_issues_modal">
    <!-- 模态框内容 -->
  </AppModal>
</template>

<script>
export default {
  mounted() {
    const assignModalEl = this.$refs.assignModal.$el;
    const getModal = new bootstrap.Modal(this.$refs.getModal.$el);

    assignModalEl.addEventListener('hidden.bs.modal', () => {
      getModal.show();
    });
  }
};
</script>

额外注意事项

  • 确保AppModal组件正确渲染Bootstrap标准模态框结构
  • Bootstrap官方不推荐嵌套模态框,优先采用模态框切换方式

内容的提问来源于stack exchange,提问作者Newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 12:57:35