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

Livewire组件mount赋值的$items在函数中丢失值的解决方法

问题原因与解决方案

问题核心在于你把$items等需要跨请求保留的状态变量声明为protected——Livewire仅会序列化并维护公共(public)属性的状态,受保护或私有属性在触发wire:click这类后续请求时,会被重置为初始值,导致$items变回空数组。

修复步骤

将所有需要跨请求保持状态的属性从protected改为public:

修改后的组件代码:

class Portfolio extends Component
{
    public $main_item_id;
    public $items=[];
    public $rotationAngle = 0;
    public $rotationDiff = 0;
    public $rotates=[];
    public $translateXs=[];
    public $translateYs=[];

    public function mount(){
        $projects = Project::all();
        $this->main_item_id=0;
        $this->items=json_decode(json_encode($projects),true);
        $this->rotationAngle = 3*M_PI/2;
        $this->rotationDiff = 2*M_PI/count($this->items);
        $this->setTransform();
    }

    public function rotateItemsRight()
    {
        $this->rotationAngle += $this->rotationDiff;
        $this->main_item_id--;
        $this->main_item_id%=count($this->items);
        $this->setTransform();
        
    }
    
    public function render()
    {
        return view('livewire.portfolio',[
            'items' => $this->items,
            'main_item_id' => $this->main_item_id,
            'rotationAngle' => $this->rotationAngle,
            'rotationDiff' => $this->rotationDiff,
            'rotates' => $this->rotates,
            'translateXs' => $this->translateXs,
            'translateYs' => $this->translateYs
        ])->extends('layouts.app');
    }
}

补充说明

  • Livewire依赖序列化public属性实现跨请求状态维护,非公共属性无法被序列化,每次请求都会重新初始化。
  • 若部分属性无需暴露给前端模板,可使用Livewire 3+的#[Ignore]标记避免序列化,示例:
    #[Ignore]
    public $someInternalVariable;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 21:36:31