Livewire & Laravel 8:更新全局组件

Livewire & Laravel 8: updating global components

我对组件和 livewire 游戏还很陌生,所以当我需要从其他来源更新组件值时,我会感到非常困惑。让我解释一下:

我使用默认 Laravel 8 安装 Livewire - 没有 JetStream。

我的导航文件(安装时自带的默认文件)有 3 个单独的组件,包含:获得的总点数、总生命数和剩余生命数。

加载如下:

<x-points>0</x-points>

<x-lifes>0</x-lifes>

<x-remaining-lifes>0</x-remainung-lifes>

我的问题:当我执行来自不同来源的操作时,如何更新这些组件,例如:

我会为 livewire 组件更改您的三个主要 blade 组件:

<livewire:points></livewire:points>

<livewire:lifes></livewire:lifes>

<livewire:remaining-lifes></livewire:remaining-lifes>

例如,让我们创建 pointsanswer 组件。

// Points.php livewire component

public int points = 0;

public $listeners = ['loadUserPoints'];

public function render() { ... }

public function loadUserPoints()
{
     $this->points = user()->points()->sum('total');
}
// points.blade.php livewire component

<div wire:init="loadUserPoints">{{ $points }}</div>

现在让我们抽象 answer 组件。

// answer livewire component (very abstracted)

public function save()
{
     user()->answers()->create($this->data);

     // this will be listened by the points component
     // that will run its query and update your frontend
     $this->emit('loadUserPoints');
}

所以livewire主要是为事件工作的,你必须用它来跨多个组件传递数据。要将您的前端更新为 SPA,您不会使用 blade 组件,您必须使用 livewire 组件或大量 javascript 来处理 DOM.