bmatovu/laravel-js-routes

Laravel JavaScript 路由。

v2.2.1 2023-05-01 17:33 UTC

This package is auto-updated.

Last update: 2024-08-30 01:23:26 UTC


README

Build Status Scrutinizer Code Quality Code Coverage StyleCI Documentation

此最小化包将帮助您通过JavaScript访问现有的PHP路由。

安装

通过Composer包管理器安装

composer require bmatovu/laravel-js-routes

设置

在环境文件.env中设置应用程序URL。

APP_URL="https://:8000"

将应用程序URL添加到基本布局的head meta中;通常在resources/views/layouts/app.blade.php中。

<meta name="app-url" content="{{ config('app.url') }}">

生成路由

php artisan js-routes:generate

路由将被写入一个json文件:resources/js/routes.json

您应该将上述自动生成的文件添加到.gitignore中。

发布资源

将JavaScript路由器发布到resources/js

php artisan vendor:publish --provider="Bmatovu\JsRoutes\JsRoutesServiceProvider"

使用Webpack | Laravel Mix

加载JavaScript路由器;通常在resources/js/app.js中。

window.route = require('./router.js').route;

console.log(route('login'));

使用ViteJS

import { route } from './router.mjs';
window.route = route;

console.log(route('login'));

编译JS路由

npm run dev

用法

示例Laravel(命名)路由

$int = '^\d+$';

Route::pattern('post', $int);
Route::pattern('comment', $int);

Route::group(['prefix' => 'posts', 'as' => 'posts.'], function () {
    Route::get('/', 'PostController@index')->name('index');
    Route::get('/{post}/comments/{comment?}', 'PostController@comments')->name('comments');
    Route::delete('/{post}', 'PostController@destroy')->name('destroy');
});

在JavaScript中;只需通过名称获取路由。

axios.get(route('posts.index'));
// https://:8000/posts

axios.get(route('posts.comments', {'post': post.id}));
// https://:8000/posts/1/comments

axios.get(route('posts.comments', {'post': post.id, 'comment': comment.id}));
// https://:8000/posts/1/comments/4

axios.get(route('posts.comments', {'post': post.id, 'comment': comment.id, 'page': 2, 'size': 10}));
// https://:8000/posts/1/comments/4?page=2&size=10

axios.delete(route('posts.destroy', {'post': post.id}));
// https://:8000/posts/1

axios.get(route('posts.index', {'published-at': '2020-09-23 16:42:12'}));
// https://:8000/posts?published-at=2020-09-23%2016:42:12

axios.get(route('posts.index', {'with': ['author', 'comments']}));
// https://:8000/posts?with=author,comments

axios.get(route('posts.index', {'with[0]': 'author', 'with[1]': 'comments'}));
// https://:8000/posts?with[0]=author&with[1]=comments