Skip to content
全部文档

重定向

用户完成某些操作(例如提交表单)后,你可能希望把他们重定向到应用中的另一页。

因为 Livewire 请求不是标准的整页浏览器请求,普通的 HTTP 重定向不起作用。你需要通过 JavaScript 触发重定向。好在 Livewire 提供了简单的 $this->redirect() 辅助方法,可在组件内使用;内部会在前端完成重定向流程。

如果你愿意,也可以在组件中使用 Laravel 内置的重定向工具

基本用法

下面是一个 post.create Livewire 组件示例:用户提交表单创建文章后,重定向到另一页:

php
<?php

use Livewire\Component;
use App\Models\Post;

new class extends Component {
	public $title = '';

    public $content = '';

    public function save()
    {
		Post::create([
			'title' => $this->title,
			'content' => $this->content,
		]);

		$this->redirect('/posts'); // [tl! highlight]
    }
};
?>

<form wire:submit="save">
    <!-- Form fields... -->
</form>

可以看到,触发 save 动作时也会触发到 /posts 的重定向。Livewire 收到该响应后,会在前端把用户带到新 URL。

按路由重定向

若要按路由名称重定向到某个页面,可以使用 redirectRoute

例如,若有一个名为 'profile' 的路由:

php
    Route::get('/user/profile', function () {
        // ...
    })->name('profile');

可以用 redirectRoute 按路由名重定向到该页:

php
    $this->redirectRoute('profile');

若需要向路由传参,可使用 redirectRoute 的第二个参数:

php
    $this->redirectRoute('profile', ['id' => 1]);

重定向到意图页

若要把用户带回他们之前所在的页面,可以使用 redirectIntended。它接受可选的默认 URL 作为第一个参数;若无法确定上一页,则回退到该 URL:

php
    $this->redirectIntended('/default/url');

重定向到整页组件

因为 Livewire 使用 Laravel 内置的重定向功能,你可以在典型 Laravel 应用中使用的所有重定向方法在这里同样可用。

例如,若把 Livewire 组件用作某条路由的整页组件:

php
Route::livewire('/posts', 'pages::show-posts');

只需使用路由路径即可重定向过去:

php
public function save()
{
    // ...

    $this->redirect('/posts');
}

重定向到控制器动作

若要重定向到由控制器动作处理的路由,可以使用 redirectAction()

php
$this->redirectAction([UserController::class, 'index']);

可以把参数作为第二个参数传给控制器动作:

php
$this->redirectAction([UserController::class, 'show'], ['id' => 1]);

闪存消息

除了可以使用 Laravel 内置的重定向方法外,Livewire 也支持 Laravel 的 session 闪存数据工具

要在重定向时附带闪存数据,可以使用 Laravel 的 session()->flash() 方法:

php
<?php

use Livewire\Component;

new class extends Component {
    // ...

    public function update()
    {
        // ...

        session()->flash('status', 'Post successfully updated.');

        $this->redirect('/posts');
    }
};
?>

假设目标页面包含下面这段 Blade,用户更新文章后会看到「Post successfully updated.」消息:

blade
@if (session('status'))
    <div class="alert alert-success">
        {{ session('status') }}
    </div>
@endif

另请参阅

  • Navigate — 用 SPA 导航做重定向
  • 动作 — 动作完成后重定向
  • 表单 — 表单提交成功后重定向
  • 页面 — 在页面组件之间导航