Laravel Livewire wire:poll导致Bootstrap模态窗口自动关闭的解决办法
问题解决:阻止wire:poll导致Bootstrap模态框自动关闭
问题根源
你的代码存在两个核心问题导致模态框被wire:poll刷新关闭:
wire:poll直接包裹在按钮内部,每次poll触发时,整个按钮及内部DOM会被重新渲染,Bootstrap模态框绑定的原始DOM元素被替换,自然会触发关闭。- 循环生成的模态框共用同一个ID
registerModal,不仅会导致点击不同按钮都打开同一个模态框,刷新时还会引发DOM冲突。
解决方案
1. 缩小wire:poll的作用范围
只把wire:poll应用在需要实时更新的状态显示区域,不要包裹按钮或模态框。这样刷新时只会更新状态部分,不会影响按钮和模态框的DOM结构。
修改按钮部分代码:
<button type="button" data-toggle="modal" data-target="#registerModal-{{ $habitacion->id }}"> <div> <!-- 仅给需要刷新的状态区域添加wire:poll --> <div wire:poll.2s class=" @if($habitacion->estado == '1') items @elseif($habitacion->estado == '2') items2 @elseif($habitacion->estado == '3') items3 @endif "> <p class="texto1">{{$habitacion->id}}</p> <p class="texto2">@if($habitacion->estado == '1') DISPONIBLE @elseif($habitacion->estado == '2') OCUPADA @elseif($habitacion->estado == '3') RESERVADA @endif</p> <p style=" @if($habitacion->estado == '1') color: #6ff96b; @elseif($habitacion->estado == '2') color: #fa595a; @elseif($habitacion->estado == '3') color: #7c98fc; @endif" class="texto3">30 MIN</p> </div> </div> </button>
2. 给模态框设置唯一ID
循环中每个模态框必须使用独特ID,确保点击对应按钮时打开正确的模态框,同时避免DOM冲突:
<!-- Modal --> <div class="modal fade register-modal" id="registerModal-{{ $habitacion->id }}" tabindex="-1" role="dialog" aria-labelledby="registerModalLabel-{{ $habitacion->id }}" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header" id="registerModalLabel-{{ $habitacion->id }}"> <h4 class="modal-title">Register - Habitación {{ $habitacion->id }}</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x"> <line x1="18" y1="6" x2="6" y2="18"></line> <line x1="6" y1="6" x2="18" y2="18"></line> </svg> </button> </div> <!-- 模态框其余内容保持不变 --> </div> </div> </div>
3. 可选:模态框打开时暂停poll(进阶优化)
如果需要完全避免poll在模态框打开时触发,可以利用Bootstrap的模态框事件和Livewire的JavaScript API控制:
在组件的blade文件底部添加脚本:
<script> document.addEventListener('DOMContentLoaded', function() { // 监听模态框显示事件,暂停poll $('.register-modal').on('show.bs.modal', function () { Livewire.emit('pausePolling'); }); // 监听模态框隐藏事件,恢复poll $('.register-modal').on('hidden.bs.modal', function () { Livewire.emit('resumePolling'); }); }); </script>
然后在对应的Livewire组件类中添加事件监听:
use Livewire\Component; class YourComponent extends Component { protected $listeners = ['pausePolling', 'resumePolling']; public function pausePolling() { $this->dispatch('stopPolling'); } public function resumePolling() { $this->dispatch('startPolling'); } // 组件其余逻辑 }
这样模态框打开时会暂停poll刷新,关闭后恢复,进一步避免不必要的DOM更新。
内容的提问来源于stack exchange,提问作者Jeremias Rosas
相关产品推荐
相关产品推荐

