如何在Laravel 11+Livewire中实现动态表格加载进度动画
在Laravel 11 + Livewire中实现分页加载动画提示
Livewire本身提供了原生的加载状态处理能力,结合CSS就能轻松实现你要的表格加载动画效果,以下是几种实用方案:
一、基础加载遮罩提示
利用Livewire的wire:loading指令,在分页加载时显示全局遮罩或文本提示:
视图代码
<div class="relative"> <!-- 加载遮罩 --> <div wire:loading class="absolute inset-0 bg-white/80 flex items-center justify-center z-10"> <span class="text-gray-600">加载中...</span> </div> <!-- 数据表格 --> <table class="w-full border-collapse"> <thead> <tr class="bg-gray-100"> <th class="border p-3">ID</th> <th class="border p-3">名称</th> <th class="border p-3">创建时间</th> </tr> </thead> <tbody> @foreach($items as $item) <tr class="hover:bg-gray-50"> <td class="border p-3">{{ $item->id }}</td> <td class="border p-3">{{ $item->name }}</td> <td class="border p-3">{{ $item->created_at->format('Y-m-d') }}</td> </tr> @endforeach </tbody> </table> <!-- Livewire分页组件 --> <div class="mt-4"> {{ $items->links() }} </div> </div>
配套CSS
.relative { position: relative; }
二、表格骨架加载动画(模拟灰色渐变行)
这种方案更贴近你提到的“表格行灰色渐变加载动画”,通过切换真实表格和骨架表格实现:
视图代码
<div class="w-full"> <!-- 真实数据表格:加载时隐藏 --> <table class="w-full border-collapse" wire:loading.remove> <thead> <tr class="bg-gray-100"> <th class="border p-3">ID</th> <th class="border p-3">名称</th> <th class="border p-3">创建时间</th> </tr> </thead> <tbody> @foreach($items as $item) <tr class="hover:bg-gray-50"> <td class="border p-3">{{ $item->id }}</td> <td class="border p-3">{{ $item->name }}</td> <td class="border p-3">{{ $item->created_at->format('Y-m-d') }}</td> </tr> @endforeach </tbody> </table> <!-- 骨架表格:加载时显示 --> <table class="w-full border-collapse" wire:loading> <thead> <tr class="bg-gray-100"> <th class="border p-3"><div class="skeleton w-10"></div></th> <th class="border p-3"><div class="skeleton w-40"></div></th> <th class="border p-3"><div class="skeleton w-32"></div></th> </tr> </thead> <tbody> <!-- 生成5行模拟骨架 --> @for($i = 0; $i < 5; $i++) <tr> <td class="border p-3"><div class="skeleton w-10"></div></td> <td class="border p-3"><div class="skeleton w-40"></div></td> <td class="border p-3"><div class="skeleton w-32"></div></td> </tr> @endfor </tbody> </table> <!-- 分页组件:加载时禁用按钮防止重复点击 --> <div class="mt-4"> {{ $items->links('pagination::bootstrap-5', ['attributes' => ['wire:loading.attr' => 'disabled', 'wire:loading.class' => 'opacity-50 cursor-not-allowed']]) }} </div> </div>
骨架动画CSS
.skeleton { height: 18px; border-radius: 4px; background: linear-gradient(90deg, #f0f0f0 25%, #e5e5e5 50%, #f0f0f0 75%); background-size: 200% 100%; animation: skeleton-shimmer 1.5s infinite linear; } @keyframes skeleton-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
三、精准控制加载目标(避免全局触发)
如果页面还有其他Livewire交互,可通过wire:target指定仅在分页操作时触发加载状态:
<!-- 仅当调用gotoPage方法(分页点击)时显示遮罩 --> <div wire:loading.target="gotoPage" class="absolute inset-0 bg-white/80 flex items-center justify-center z-10"> <span class="text-gray-600">加载中...</span> </div>
内容的提问来源于stack exchange,提问作者Rui Alves
相关产品推荐
相关产品推荐

