【问题标题】:Livewire: Unable to update child components after adding new recordLivewire:添加新记录后无法更新子组件
【发布时间】:2020-11-12 08:16:57
【问题描述】:

我有一个无法解决的问题。我已将组件结构设置为:

发布 -> 评论 -> 评论回复

CommentReply 发出 Post 捕获的事件。发布更新 cmets 集合。

评论(模型)具有自我关系作为响应。

现在,如果评论是顶级的,则视图会更新。但是,如果响应关系被更新,则视图不会显示更新。如果我在Comment(组件)中发出一个映射到$refresh 的刷新事件,则组件会抛出错误:

Uncaught (in promise) TypeError: Cannot read property 'fingerprint' of null

更新

CommentReply.php

public function post_reply () {
     ...
    $new_comment = $this->comment->response()->create($c);
    $this->is_replying = false;
    $this->emit('content:comments:replied', $new_comment);
}

Comment.php(组件)

    public $listeners = [
        'content:comments:replied' => 'replied'
    ];

   public function replied($comment) {
        /*
           received as array because type hinting
           created error of array to string conversion
       */
        $c = new CommentModel($comment); 
        $this->comment->responses->prepend($c);
    }

comment.blade.php

<div>
@foreach($comment->responses as $response)
<div>
     <div>
         {{ $response->comment }}
     </div>

     <livewire:comment-reply :comment="$comment" :key="'comment-' . $response->id" />
</div>
@endforeach
</div>

comment-reply.blade.php

<div x-data="{ replying: @entangle('is_replying') }">
    <button @click="replying = true;" x-show="!replying">Reply</button>
   <div x-show="replying">
       <textarea wire:model.defer="c.comment"></textarea>
       <button wire:click="post_reply">Post</button>
    </div>
</div>

【问题讨论】:

标签: laravel laravel-livewire


【解决方案1】:

这就是我的做法......

  1. 创建了一个组件CommentView,并将评论显示逻辑移到了这个组件上 comment-view.blade.php
<div>
     <div>
         {{ $comment->comment }}
     </div>

     <livewire:comment-reply :comment="$comment" />
</div>
  1. Comment 组件现在有两个变量,$comment$responses,每次 CommentReply 发出 content:comments:replied 时,$responses 变量都会刷新。

Comment.php

    public $listeners = [
        'content:comments:replied' => 'replied'
    ];

   public function replied() {
        $this->responses = $this->comment->responses()->orderBy('created_at', 'desc')->get();
    }

comment.blade.php

<div>
    <livewire:comment-view :comment="$comment" />
    @foreach($responses as $r_comment) 
          <livewire:comment-view :comment="$r_comment" :key="'response-' . $r_comment->id" />
     @endforeach
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    相关资源
    最近更新 更多