如何在Laravel Splade中实现按钮点击触发模态框
Laravel Splade 实现按钮点击弹出模态框方案
直接用Splade内置的<x-splade-modal>组件就能实现需求,不需要依赖<x-splade-toggle>。以下是修改后的完整代码:
<x-layout> <x-panel> <h1>Today's news items</h1> <!-- 触发模态框的按钮 --> <button @click="$modal.open('notifications-modal')">Toggle notifications</button> <!-- Splade 模态框组件 --> <x-splade-modal name="notifications-modal" title="Latest Notifications"> <x-splade-lazy> @php $notifications = [ 'Got a news about laravel splade', 'Got a news about laravel splade this is best', ]; @endphp <x-slot:placeholder> <p>Loading notifications...</p> </x-slot:placeholder> @foreach($notifications as $notification) <div class="mb-2">{{ $notification }}</div> @endforeach </x-splade-lazy> </x-splade-modal> </x-panel> </x-layout>
关键说明:
- 用Splade全局API
$modal.open('modal-name')触发指定名称的模态框,模态框组件的name属性必须和触发方法里的名称完全匹配 <x-splade-modal>自带弹窗样式、关闭按钮和背景遮罩,无需额外写CSS- 保留了你原来的
<x-splade-lazy>逻辑,只有当模态框打开时才会加载内容,优化性能 - 可以通过
title属性快速设置模态框标题,也可以自定义头部插槽<x-slot:header>实现更复杂的头部内容 - 如果想用Splade自带的按钮样式,把普通按钮换成
<x-splade-button modal="notifications-modal">Toggle notifications</x-splade-button>即可,无需写@click事件
内容的提问来源于stack exchange,提问作者Abid Raheem
相关产品推荐
相关产品推荐

