8

I have an alert component that I hide using AlpineJS but I want it to be visible again after Livewire re-renders.

Showing the alert using Livewire component

@if(Session::has('success'))
    <x-success-alert :message="Session::get('success')" />
@endif

AlpineJS component

<div x-data="{show: true}">
    <div x-show="show">
        <span>{{ $message }}</span>
        <button @click="show = false">&times;</button>
    </div>
</div>
1
  • you can't, a component is initialized only once. Commented Feb 13, 2022 at 10:32

2 Answers 2

28

The solution is to force Livewire to add that element in the dom again by adding wire:key to a random value.

<div wire:key="{{ rand() }}">
    <div x-data="{show: true}">
        <div x-show="show">
            <span>{{ $message }}</span>
            <button @click="show = false">&times;</button>
        </div>
    </div>
</div>

With that way, Livewire will destroy the old dom element and add the new one which re-init the Alpine component.

Sign up to request clarification or add additional context in comments.

5 Comments

This was helpful but I changed it up a bit. I used md5 and json_encode to check to see if the data had actually changed: wire:key="{{ md5(json_encode($message)) }}"
This is the best answer imho
I used this and it caused another element to be duplicated after each component re-init. any other idea?
wire:key doesn't effect other elements, the issue might not be with that.
I totally forgot to add the key to the loop items. Thanks for reminding!
0

Just in case this helps anyone else, I have found that if an alpine component within a Livewire component is removed from the dom, it is not loaded correctly if reinstated *if the x-data directive is applied to the outermost element.

So, for example, just wrap the <x-success-alert> component in an additional div:

<div>
    <div x-data="{show: true}">
        <div x-show="show">
            <span>{{ $message }}</span>
            <button @click="show = false">&times;</button>
        </div>
    </div>
</div>

1 Comment

Although I couldn't see how is this relevant to the question asked... thanks for the insight. BTW Have you noticed the same behavior with wire:key too?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.