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

Vue3集成jQuery+Bootstrap调用Modal报错:modal is not a function

解决Vue3中Bootstrap Modal调用报错:modal is not a function

问题描述

开发Vue3应用时,已安装jQuery和Bootstrap并在main.js中引入,点击AdminView组件的「Create Product」按钮调用子组件ProductModal的showProductModel方法时,出现报错:

jquery__WEBPACK_IMPORTED_MODULE_2___default(...)(...).modal is not a function
TypeError: jquery__WEBPACK_IMPORTED_MODULE_2___default(...)(...).modal is not a function
  at Proxy.showProductModel

报错原因分析

  1. Bootstrap未绑定到正确的jQuery实例:Bootstrap的JS组件依赖jQuery,但引入顺序错误或全局挂载方式不当,导致Bootstrap无法将modal等方法绑定到jQuery原型上。
  2. 多jQuery实例冲突:组件内重复导入jQuery,Webpack打包生成多个独立的jQuery实例,而Bootstrap仅绑定了main.js中初始化的实例。
  3. Bootstrap依赖缺失:从提供的package.json来看,Bootstrap未出现在依赖列表中,可能未完成安装或未正确添加到项目依赖。

解决方案

1. 确保Bootstrap已正确安装

如果尚未安装Bootstrap,执行以下命令:

npm install bootstrap

安装后检查package.json的dependencies字段,确认bootstrap已存在:

"dependencies": {
  "bootstrap": "^5.x.x",
  "jquery": "^3.7.1",
  // 其他项目依赖...
}

2. 修复main.js中jQuery与Bootstrap的引入顺序

Bootstrap必须在jQuery全局挂载完成后再引入,修改main.js代码:

// 先挂载jQuery到全局
import $ from 'jquery'
window.$ = $
window.jQuery = $

// 再引入Bootstrap的JS和CSS
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'

3. 移除组件内重复的jQuery导入

删除AdminView和ProductModal组件内的jQuery导入代码:

  • AdminView组件中删除:
    import jquery from "jquery";
    const $ = jquery;
    window.$ = $;
    
  • ProductModal组件中删除:
    import $ from "jquery";
    

组件内直接使用全局的$即可。

4. 可选:确保Modal元素已渲染完成

在showProductModel方法中使用$nextTick确保DOM更新后再调用modal:

showProductModel() {
  console.log("child component");
  this.$nextTick(() => {
    $('#productModal').modal('show');
  });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:23:16