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

tightenco/ziggy配置后模板异常显示完整地址列表求助

问题排查与解决方案

1. 检查@routes指令的输出格式

打开浏览器开发者工具查看页面源码,确认@routes生成的是带type="application/json"属性的script标签,而非直接输出JSON文本。正常输出应该类似:

<script type="application/json" id="ziggy">{"url":"http://your-app.test","port":null,"routes":{...}}</script>

如果发现是直接输出JSON字符串(未被script标签包裹),执行以下操作:

  • 确认Tightenco\Ziggy\ZiggyServiceProvider已在config/app.php的providers数组中注册(Laravel 5.5+会自动发现,无需手动注册)。
  • 清除视图缓存:执行php artisan view:clear。

2. 修正Inertia环境下的Ziggy配置

在Inertia项目中,无需在视图中使用@routes指令——Inertia会通过共享数据传递路由信息,重复使用@routes可能导致JSON数据意外暴露。

调整步骤:

  • 从HTML视图的<head>中移除@routes代码。
  • 在Laravel后端的HandleInertiaRequests中间件中,添加Ziggy路由数据到共享数据:
// app/Http/Middleware/HandleInertiaRequests.php
use Tightenco\Ziggy\Ziggy;

public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'ziggy' => fn () => new Ziggy(['request' => $request]),
    ]);
}
  • 在前端app.js中,移除手动导入的Ziggy对象,改为从Inertia的共享数据中获取:
// resources/js/app.js
import { createApp, h } from 'vue'
import { createInertiaApp } from '@inertiajs/vue3'
import { ZiggyVue } from 'ziggy'

createInertiaApp({
  resolve: name => require(`./Pages/${name}.vue`),
  setup({ el, App, props, plugin }) {
    return createApp({ render: () => h(App, props) })
      .use(plugin)
      .use(ZiggyVue, props.ziggy) // 从Inertia props中获取ziggy数据
      .mount(el)
  },
})

3. 修正Vite别名配置

确保Vite的Ziggy别名路径正确,避免加载错误文件导致异常:

// vite.config.js
import path from 'path';

export default {
  resolve: {
    alias: {
      ziggy: path.resolve('vendor/tightenco/ziggy/dist/vue.es.js'), // 移除路径开头的斜杠
    },
  },
}

路径开头不要加斜杠,否则会从系统根目录查找,而非项目根目录。

4. 清除缓存并重启服务

  • 执行php artisan cache:clear清除应用缓存
  • 重启Vite开发服务器和Laravel服务,确保配置生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:20:34