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

如何在Livewire中动态渲染Title属性?

解决Livewire组件动态设置页面标题的问题

你可以通过两种方式实现页面标题随文章动态变化:

方法一:用闭包形式的#[Title]注解

直接在#[Title]里传入闭包,闭包可访问组件的post属性,动态返回文章标题:

<?php

namespace App\Livewire\Posts;

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

class ShowPost extends Component
{
    public $post;

    public function mount(Post $post)
    {
        $this->post = $post;
    }

    #[Title(fn($component) => $component->post->title)]
    public function render()
    {
        return view('livewire.posts.show-post', [
            'post' => $this->post,
        ]);
    }
}

方法二:在render方法中调用title()方法

移除硬编码的#[Title]注解,在render里通过$this->title()动态设置标题:

<?php

namespace App\Livewire\Posts;

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

class ShowPost extends Component
{
    public $post;

    public function mount(Post $post)
    {
        $this->post = $post;
    }

    public function render()
    {
        $this->title($this->post->title);
        
        return view('livewire.posts.show-post', [
            'post' => $this->post,
        ]);
    }
}

为什么之前Blade传值不生效?

Livewire会接管页面标题的设置逻辑,你在Blade模板里传递title变量或使用@section('title'),若未与Livewire的标题机制配合,会被Livewire的设置覆盖。上面两种方法都是利用Livewire官方提供的动态标题方案,能确保标题跟随post内容正确变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 21:19:51