Laravel 和 Inertia 在 Vue 内创建路线

Fos*_*nce 0 inertiajs laravel vue.js

我用 Inertia 安装了 Laravel。我在里面得到了这个resources/js/app.js

\n
require('./bootstrap');\n\n// Import modules...\nimport { createApp, h } from 'vue';\nimport { App as InertiaApp, plugin as InertiaPlugin } from '@inertiajs/inertia-vue3';\nimport { InertiaProgress } from '@inertiajs/progress';\n\nconst el = document.getElementById('app');\n\ncreateApp({\n    render: () =>\n        h(InertiaApp, {\n            initialPage: JSON.parse(el.dataset.page),\n            resolveComponent: (name) => require(`./Pages/${name}`).default,\n        }),\n})\n    .mixin({ methods: { route } })\n    .mixin(require('./translation'))\n    .use(InertiaPlugin)\n    .mount(el);\n\nInertiaProgress.init({ color: '#4B5563' });\n\n
Run Code Online (Sandbox Code Playgroud)\n

正如您可能看到的那样.mixin({ methods: { route } })。我可以用来this.route('name.of.route')从 \xcb\x99routes` 文件夹生成命名路由。

\n

我想修改route方法以在每次生成路由时默认添加前缀。如何调整 Inerta 的route方法。

\n

Sol*_*lar 5

使用 Inertia,所有路由都在服务器端定义。这意味着你不需要 Vue Router 或 React Router。只需使用您选择的服务器端框架创建路由即可。

您可以在这里阅读更多相关信息(https://inertiajs.com/routing#top

由于ziggy 库,您已经安装了 javascript 上的所有可用路线。route()它提供了一个与 Laravel 类似的JavaScript辅助函数,让您可以轻松地在 JavaScript 中使用 Laravel 命名路由。

要修改或添加 URL 前缀,您必须使用 Middleware 或Route Groups从后端(Laravel)执行此操作,因为 Ziggy 不会创建 URL,它只是提供您在 Laravel 的 web.php 中定义的 URL文件在你的Javascript中。

这就是您@routes的根刀片文件中包含此文件的原因。如果你删除它,this.routes或者this.$routes将不可用。

例如

Route::group(['prefix' => 'admin'], function () {
    Route::inertia('/dashboard', 'Dashboard')->name('admin.dashboard');
});
Run Code Online (Sandbox Code Playgroud)

这意味着该 URL 将在以下位置可用/admin/dashboard,您可以使用 Javascript 访问它this.route('admin.dashboard')

或者阅读有关 Ziggy 包的更多信息,以获得所需的结果。

值得一提的是,您可以用您喜欢的任何名称来命名路线。只需确保您在内部传递的内容与->name('')调用时使用的内容相同即可this.route()