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

Vue3(Vite)集成Bootstrap5调用模态框报错:Cannot read 'backdrop'

Vue3+Vite+Bootstrap5 模态框问题修复方案

1. 先搞定Bootstrap JS的导入问题

Vite环境下直接导入bootstrap没法自动初始化JS组件,而且Bootstrap 5的模态框依赖Popper.js,得先把依赖补全:

  • 安装Popper:
npm install @popperjs/core
  • 在main.js里正确导入CSS和JS:
// 导入Bootstrap样式
import 'bootstrap/dist/css/bootstrap.css'
// 导入Bootstrap所有JS组件,自动关联Popper
import * as bootstrap from 'bootstrap'
// 可选:把bootstrap挂载到全局,方便组件里调用
app.config.globalProperties.$bootstrap = bootstrap

2. 修复模态框组件的核心错误

你的组件里有几个明显的问题,直接导致了backdrop报错:

问题1:实例存储变量放错地方了

components选项是用来注册子组件的,不能存Modal实例,要放到data里:

data() {
  return {
    myModal: null // 在这里存Modal实例
  }
}

删掉components里的myModal: null。

问题2:watch监听逻辑完全不对

当前watch里的this.cam_prop = newVal.properties和模态框半毛钱关系没有,应该根据show的值控制模态框显示/隐藏:

watch: {
  show(newVal) {
    if (newVal) {
      this.myModal.show()
    } else {
      this.myModal.hide()
    }
  }
}

问题3:模板里别用this.访问props

Vue模板里直接写props名称就行,不用加this.:

<template>
  <div ref="modalEl" class="modal" tabindex="-1" aria-labelledby="ErrorModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Error {{ occurred }}</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <p>{{ error_message }}</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">OK</button>
        </div>
      </div>
    </div>
  </div>
</template>

问题4:别用固定ID,用ref避免DOM冲突

如果组件复用,固定IDerrModal会导致重复DOM问题,改用ref获取元素:

mounted() {
  // 通过ref拿元素,替代getElementById
  this.myModal = new Modal(this.$refs.modalEl)
}

3. 父组件调用优化

父组件里不用传id="#ErrModal",模板里也别加this.访问data属性:

<RegIdentErrorModalVue 
  :show="error" 
  occurred="Identification" 
  :error_message="error_text"
/>

4. 解决new bootstrap.Modal未定义的问题

如果不想在组件里单独导入Modal,可以用全局挂载的$bootstrap:

this.myModal = new this.$bootstrap.Modal(this.$refs.modalEl)

改完这些,模态框就能通过show props正常控制显示隐藏,不会再出现backdrop相关的报错了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 06:30:50