livewire / alpine-plugin

AlpineJS support within Livewire components
47 stars 3 forks source link

A newly added alpine component returned from a Livewire component is never initialized #2

Open mokhosh opened 4 years ago

mokhosh commented 4 years ago

I have a simple Livewire component that returns a table. Each row has a delete button that is an alpine component. Clicking this delete button shows a confirmation modal which has a show = false data and should be hidden by default. Before I add the alpine-plugin, none of the alpine components would be initialized after dom changes, so I had to cancel a dozen delete confirmation modals every time my Livewire table updated. Now that I've added the plugin, alpine components that were in the original html are initialied, but the new one is not. If I create a new row using Livewire, its modal is open by default and its @click won't work either.

What am I doing wrong?

mokhosh commented 4 years ago

Here's a simplified version of my Livewire blade template:

@foreach($models as $model)
<tr>
    <td>{{ $model->id }}</td>
    <td>{{ $model->name }}</td>
    <td x-data="{ isDeleting: false }">
        <button @click="isDeleting = true">Delete</button>
        <div class="modal" x-show="isDeleting">
            <div class="overlay" @click="isDeleting = false"></div>

            <div class="modal-content">
                <p>Delete {{ $model->name }} model?</p>
                <button wire:click="delete({{ $model->id }})" @click="isDeleting = false">Delete</button>
            </div>
        </div>
    </td>
</tr>
@endforeach
mokhosh commented 4 years ago

This is the order in which I've imported assets:

@livewireScripts {{-- version 0.7.4 --}}
<script src="https://cdn.jsdelivr.net/gh/livewire/alpine-plugin@v0.1.0/dist/livewire-alpine-plugin.js"></script>
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.0.0/dist/alpine.js" defer></script>
mokhosh commented 4 years ago

I red the code for alpine plugin and alpine's index.js and figured a hacky way to fix this. I put an x-data attribute on my livewire components root element.

But this should work without a hack. if the root element isn't an alpine component but some parts of new html returned by livewire contains tags with x-data they should be initialized.