首页 > 解决方案 > 使用 Laravel Livewire 进行阵列管理和预览

问题描述

当使用输入文件通过 Livewire 加载图像时,我发现如果用户单击以加载多个图像,它可以正常工作,但是如果他第二次单击相同的输入,使用 Livewire 的预览将被选定的图像替换。第二次。为了解决这个问题,添加一个加载图像的数组,如下所示:

我的输入文件

<input wire:change="cargaImagenes" wire:model="imagen" type="file" name="imagen" accept="image/*" class="form-control-file" multiple>

活动费用

public function cargaImagenes()
        {
            foreach ($this->imagen as $ima) {
                array_push($this->imagenes, $ima);
            }
        }

问题是我使用 Livewire 通过以下方式预览图像:

 @if ($imagenes)
           <small>previsualización:</small>
    
           <div class="form-inline">
             @foreach($imagenes as $img)
              <div wire:key="{{$loop->index}}">
              <div class="m-2 img-thumbnail">
                <img class="my-2 rounded img-fluid contenedor-img" src="{{ $img->temporaryUrl() }}">
                  <button class="btn btn-outline-danger" wire:click="eliminarImagen({{ $loop->index }})">
                  </button>
              </div>
              </div>
             @endforeach
             <br>
            </div>
      @endif

问题是它们不会在我第一次选择图像时显示,它会在我添加更多图像时显示。

对于预览,我使用数组的 $images 属性

 array_push($this->imagenes, $ima);

你能给我一个关于我可以做些什么来显示数组中的所有图像的建议吗?

标签: phplaravellaravel-7laravel-livewire

解决方案


这应该有效。

拆线:彻底改变。

<input wire:model="imagen" type="file" name="imagen" accept="image/*" class="form-control-file" multiple>

挂钩 updatedImagen() 事件方法:

public function updatedImagen()
{
    foreach ($this->imagen as $ima) {
        $this->imagenes[] = $ima;
    }
}

推荐阅读