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

Laravel Breeze+Vue3+InertiaJS生产环境报'Cannot read $page'错误

解决Laravel Breeze + Vue3 + InertiaJS生产环境Cannot read properties of undefined (reading '$page')错误

以下是针对该问题的排查和修复方案:

1. 确认Inertia全局注册完整性

生产环境打包的Tree Shaking机制可能移除Inertia的全局注入逻辑,检查resources/js/app.js中的注册代码:

import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/inertia-vue3'
import { InertiaProgress } from '@inertiajs/progress'

createInertiaApp({
  resolve: name => require(`./Pages/${name}`),
  setup({ el, app, props, plugin }) {
    return createApp({ render: () => h(app, props) })
      .use(plugin) // 必须保留该行,它负责全局注入$page对象
      .mount(el)
  },
})

InertiaProgress.init()

使用<script setup>语法时,不能仅在局部组件导入Inertia,必须通过use(plugin)完成全局注册。

2. 验证页面数据传递逻辑

确认Laravel控制器返回的Inertia响应正常传递数据,示例:

return Inertia::render('Dashboard', [
    'user' => Auth::user(),
]);

若某页面未传递任何数据,生产环境可能导致$page未初始化,可在根布局组件添加兜底判断:

<template>
  <div>
    <header>...</header>
    <main v-if="$page">
      <slot />
    </main>
  </div>
</template>

3. 调整打包工具的Tree Shaking配置

Laravel Mix/Vite的默认生产打包可能误删Inertia必要代码,针对性调整配置:

  • 若使用Vite,修改vite.config.js:
export default defineConfig({
  plugins: [
    laravel({
      input: 'resources/js/app.js',
      refresh: true,
    }),
    vue({
      template: {
        transformAssetUrls: {
          base: null,
          includeAbsolute: false,
        },
      },
    }),
  ],
  optimizeDeps: {
    include: ['@inertiajs/inertia-vue3'], // 强制保留Inertia依赖
  },
})
  • 若使用Laravel Mix,修改webpack.mix.js:
mix.webpackConfig({
  optimization: {
    usedExports: false, // 关闭过度Tree Shaking
  },
})

4. 彻底清理缓存并重新打包

执行以下命令清除所有缓存,避免旧打包文件干扰:

rm -rf node_modules
rm package-lock.json yarn.lock
yarn install
yarn cache clean
yarn prod
php artisan view:clear
php artisan cache:clear
php artisan route:clear

5. 对比正常项目的配置差异

既然存在同技术栈的正常项目,可做以下对比排查:

  • 复制正常项目的package.json依赖版本(注意你的vue-loader配置后缺少逗号,先修正语法错误)
  • 对比resources/js/app.js、打包配置文件的代码差异
  • 检查根布局组件对$page的处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:46:03