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

Laravel+Inertia.js+Vue3项目中Bootstrap Bundle JS无法生效

解决Laravel + Vue 3 + Inertia.js中Bootstrap JavaScript功能失效问题

问题分析

你当前的核心错误是将Bootstrap当作Vue插件使用,调用了.use(bootstrap),但Bootstrap 5的JavaScript库并非Vue插件,这种用法会导致Bootstrap无法正确初始化。另外,Inertia作为单页应用,页面切换时不会刷新整个页面,新渲染的DOM元素无法被Bootstrap自动识别绑定事件,这也是下拉菜单等功能失效的原因之一。

解决方案

步骤1:修正Bootstrap的导入与注册方式

移除.use(bootstrap)调用,正确导入Bootstrap Bundle,并通过Inertia的页面加载事件全局初始化组件。

修改后的app.js代码:

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import { InertiaProgress } from '@inertiajs/progress'
// 改为用* as导入,获取Bootstrap的所有组件类
import * as bootstrap from 'bootstrap/dist/js/bootstrap.bundle'

createInertiaApp({
  resolve: name => require(`./Pages/${name}`),
  setup({ el, App, props, plugin }) {
    const vueApp = createApp({ render: () => h(App, props) })
      .mixin({
        methods: {
          hasAnyPermission: function (permissions) {
            let allPermissions = this.$page.props.auth.permissions;
            let hasPermission = false;
            permissions.forEach(item => {
              if(allPermissions[item]) hasPermission = true;     
            });
            return hasPermission;
          },
          title() {
            return "Sistem Data"
          },
        },
      })
      .use(plugin)
      .mount(el)

    // 监听Inertia页面加载完成事件,重新初始化Bootstrap组件
    vueApp.config.globalProperties.$inertia.on('page:loaded', () => {
      // 初始化下拉菜单
      document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(el => {
        new bootstrap.Dropdown(el)
      })
      // 可根据需求添加其他组件初始化,比如模态框、工具提示等
      // document.querySelectorAll('[data-bs-toggle="modal"]').forEach(el => new bootstrap.Modal(el))
    })

    // 全局暴露Bootstrap,方便组件内直接调用
    vueApp.config.globalProperties.$bootstrap = bootstrap
  },
});

InertiaProgress.init()

步骤2:可选方案——组件内局部初始化

如果只需要在特定组件中使用Bootstrap功能,也可以在组件的onMounted钩子中单独初始化:

<template>
  <div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" type="button" aria-expanded="false">
      下拉菜单
    </button>
    <ul class="dropdown-menu">
      <li><a class="dropdown-item" href="#">操作1</a></li>
      <li><a class="dropdown-item" href="#">操作2</a></li>
    </ul>
  </div>
</template>

<script setup>
import { onMounted } from 'vue'
import { Dropdown } from 'bootstrap/dist/js/bootstrap.bundle'

onMounted(() => {
  const dropdownBtn = document.querySelector('.dropdown-toggle')
  new Dropdown(dropdownBtn)
})
</script>

关键说明

  1. Bootstrap不是Vue插件:.use()方法仅适用于符合Vue插件规范的包,Bootstrap是原生JS库,直接导入即可,无需通过Vue注册。
  2. 单页应用的DOM更新问题:Inertia页面切换时仅替换部分DOM,Bootstrap的自动初始化只在页面首次加载时执行,因此需要在每次页面加载完成后手动重新初始化新DOM中的组件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 07:01:10