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

Vue中提交表单时如何关闭Bootstrap模态弹出框

失效原因

直接调用this.$refs.myModal.hide()不生效,是因为Bootstrap 5的模态框控制方法挂载在Bootstrap生成的Modal实例上,而非原生DOM元素本身。


完整修改方案

1. 修改template部分,给模态框根节点添加ref属性

<template>
  <div ref="binModal" class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">{{popupTitle}}</h5>
        <button type="button" @click="closeModal" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p><input type="text" v-model="addBinLocation"></p>
        <span v-show="errorTxt" class="error">Field cannot be empty</span>
      </div>
      <div class="modal-footer">
        <button @click="btnAdd" type="button" class="btn btn-primary">Add Location</button>
      </div>
    </div>
  </div>
</div>
</template>

2. 修改script部分,新增模态框关闭逻辑

根据你引入Bootstrap的方式二选一即可:

  • npm安装Bootstrap的场景
<script>
import { Modal } from 'bootstrap'
export default {
    props:['popupTitle'],
    data(){
      return{
        addBinLocation: '',
        errorTxt: false,
      }
    },
    methods:{
      btnAdd(){
        if(this.addBinLocation === ''){
          this.errorTxt = true;
        }
        else{
          this.$emit('addLocation', this.addBinLocation);
          this.addBinLocation = ''
          this.errorTxt = false;
          // 关闭模态框
          const modalInstance = Modal.getOrCreateInstance(this.$refs.binModal)
          modalInstance.hide()
        }
    },
    closeModal(){
      this.addBinLocation = ''
      this.errorTxt = false;
    }
  }
}
</script>
  • CDN引入Bootstrap的场景
    不需要顶部导入Modal,直接使用全局挂载的bootstrap对象即可,else分支的代码替换为:
this.$emit('addLocation', this.addBinLocation);
this.addBinLocation = ''
this.errorTxt = false;
// 关闭模态框
const modalInstance = window.bootstrap.Modal.getOrCreateInstance(this.$refs.binModal)
modalInstance.hide()

补充说明

使用getOrCreateInstance而非直接new Modal可以避免重复创建模态框实例导致的报错问题,调用hide()后Bootstrap会自动处理模态框隐藏、背景遮罩移除等全链路逻辑。

内容的提问来源于stack exchange,提问作者Muhammad Ameen Sheikh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:06:03