Nuxt3 SSR模式下操作Bootstrap Modal遇document is not defined错误求助
Nuxt3 SSR模式下Bootstrap模态框切换报错
document is not defined的解决方法 问题原因
在Nuxt3 SSR模式下,页面会先在服务器端渲染,而服务器环境不存在浏览器的document对象。你的代码中模块级别的import { Modal } from 'bootstrap'会在服务端执行阶段被加载,Bootstrap的JS源码在初始化时就会尝试访问document,直接触发报错——即便你把模态框实例化逻辑放在onMounted(仅客户端执行)中,导入语句的执行时机早于客户端挂载阶段。
解决方案
方法1:动态导入Bootstrap Modal(推荐)
将Bootstrap Modal的导入逻辑移到onMounted内部,通过动态导入确保代码仅在客户端执行,避免服务端加载时访问document:
<template> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> Launch demo modal </button> <div class="modal fade" ref="exampleModal" id="exampleModal" data-bs-backdrop="static" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> 模态框内容 </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </template> <script setup lang="ts"> const exampleModal = ref<Element | null>(null) onMounted(async () => { if (!exampleModal.value) return // 仅在客户端动态导入Bootstrap Modal模块 const { Modal } = await import('bootstrap') const myModal = new Modal(exampleModal.value) myModal.toggle() }) </script>
方法2:通过CDN在客户端注入Bootstrap JS
如果不想通过npm管理Bootstrap JS,可以直接在客户端注入CDN脚本,避免服务端加载:
<template> <!-- 模态框结构同上 --> </template> <script setup lang="ts"> import { useHead } from 'nuxt/app' // 仅在客户端注入Bootstrap JS脚本 useHead({ script: [ { src: 'https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js', body: true, crossorigin: 'anonymous' } ] }, { mode: 'client' }) const exampleModal = ref<Element | null>(null) onMounted(() => { if (!exampleModal.value) return // 直接使用全局的bootstrap对象 const myModal = new window.bootstrap.Modal(exampleModal.value) myModal.toggle() }) </script>
方法3:页面级禁用SSR(仅特殊页面适用)
如果仅当前页面不需要SSR,可以在页面组件的配置中单独禁用:
<script setup lang="ts"> // 仅当前页面关闭SSR definePageMeta({ ssr: false }) // 原有的模态框逻辑(无需修改导入) import { Modal } from 'bootstrap' const exampleModal = ref<Element | null>(null) onMounted(() => { if (exampleModal.value) { const myModal = new Modal(exampleModal.value) myModal.toggle() } }) </script>
内容的提问来源于stack exchange,提问作者Phuong Bui
相关产品推荐
相关产品推荐

