我有 Livewire Volt 基于类的组件 post-form,其中包含用于创建帖子的表单。创建帖子后,我会分派 postCreated。在我的全页 Livewire 组件 GroupPage 中,我...
我有基于 Livewire Volt 类的组件, post-form
它具有创建帖子的表单。创建帖子后,我会调度 postCreated
。在我的全页 Livewire 组件中 GroupPage
,我想刷新它以便显示新创建的帖子,但它没有刷新。
后表单组件:
use Livewire\Volt\Component;
use App\Models\Group;
use App\Models\Post;
use Illuminate\Support\Facades\Auth;
new class extends Component {
public $group_id;
public $content = '';
public function mount($group_id) {
$this->group_id = $group_id;
}
public function createPost() {
$user_id = Auth::id();
$group = Group::find($this->group_id);
// Validate the request
// Create the post
$post = Post::create([
'content' => $validated['content'],
'group_id' => $this->group_id,
'user_id' => $user_id,
]);
$this->dispatch('postCreated');
}
};
GroupPage 组件:
namespace App\Livewire\Pages;
use App\Models\Post;
use App\Models\Group;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
class GroupPage extends Component
{
protected $listeners = ['postCreated' => '$refresh'];
public $group_id = '';
public function mount($group_id)
{
$this->group_id = $group_id;
}
/**
* Renders the posts that have the foreign key of $group_id
*
* @return view
*/
public function render()
{
$posts = Group::findOrFail($this->group_id)
->posts()
->latest()
->get();
return view('livewire.pages.group-page', compact(['posts']))->layout('layouts.app');
}
}