LoginSignup
2
1

More than 1 year has passed since last update.

Laravel Livewire + dropify で気をつけないとハマる

Posted at

Livewire でファイルアップロードしようと思いまして dropify でフロント側は実装したろ、と思ってみたところ、どうやっても表示が崩れて数時間悩んだんですが、結果的にこうなりました。

import $ from "jquery";
import 'dropify'

// Dropify
window.onload = () =>{
    initDropify()
}

function initDropify() {
    return $('.dropify').dropify()
}

ダメなやつ

<!-- エラー文 -->
@if($errors->any())
<div class="error">
    @foreach ($errors->all() as $error)
    <p class="error_text">{{ $error }}</p>
    @endforeach
</div>
@endif

<!-- フォーム -->
<form class="from" wire:submit.prevent="save">
    <dl class="table">
        <dd class="table_data">
            <div class="table_inner" wire:ignore>
                <input type="file" class="dropify img" wire:model="image">
            </div>
        </dd>
    </dl>
</form>

動くやつ

<!-- エラー文 -->
<div class="error" @if( ! $errors->any()) style="display:none" @endif>
    @foreach ($errors->all() as $error)
    <p class="error_text">{{ $error }}</p>
    @endforeach
</div>

<!-- フォーム -->
<form class="from" wire:submit.prevent="save">
    <dl class="table">
        <dd class="table_data">
            <div class="table_inner" wire:ignore>
                <input type="file" class="dropify img" wire:model="image">
            </div>
        </dd>
    </dl>
</form>

解説

どうも dropify というか jQuery のような気がしますが、セレクタが DOM の頂点から位置が変わってしまうと表示をうまくキープできないようでした。
上記のダメなパターンの場合、フォームの前にバリデーションなどでエラーが起きると div が差し込まれるわけですが、このとき $('.dropify').dropify() が動かなくなります。

wire:ignore を入れておかないとコンポーネントのアップデートが走った時に初期化されてしまうので、抑制もお忘れなく。
いやー酷い目にあった。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1