微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Livewire:添加新记录后无法更新子组件

如何解决Livewire:添加新记录后无法更新子组件

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

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

CommentReply发出Post捕获的事件。发布更新评论集。

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

现在,如果注释为顶级,则视图将更新。但是,如果响应关系已更新,则视图不会显示更新。如果我发出一个刷新事件,该事件映射到$refresh(组件)中的Comment,则组件引发错误

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>

解决方法

这就是我的经历...

  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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。