matierenoire/laravel-livewire-swal

此包为您的Livewire组件提供简单的警报实用工具。

dev-main 2024-09-11 10:14 UTC

This package is not auto-updated.

Last update: 2024-09-25 10:26:05 UTC


README

直接灵感来源于: https://github.com/jantinnerezo/livewire-alert

🚀 安装

您可以通过composer安装此包

composer require matierenoire/laravel-livewire-swal

需求

此包在内部使用Livewire。请在使用此包之前确保将其包含在依赖项中。

  • PHP 7.2或更高版本

  • Laravel 7, 8, 9, 10, 11

  • Livewire

  • SweetAlert2

用法

包含组件

在livewire脚本指令之后插入Sweet2Alert2和Livewire警报脚本组件。

SweetAlert2脚本默认不包含,确保在之前包含它

<body>
  ... @livewireScripts ...

  <script src="https://cdn.jsdelivr.net.cn/npm/sweetalert2@10"></script>
  ...
  <x-livewire-alert::scripts />
</body>

发布配置文件

php artisan vendor:publish --provider="MN\LivewireAlert\LivewireAlertServiceProvider" --tag="config"

显示警报

您可以尝试SweetAlert2的配置。

$this->alert('success', 'Hello World!', [
      'position' =>  'top-end',
      'timer' =>  3000,
      'toast' =>  true,
      'text' =>  '',
      'confirmButtonText' =>  'Ok',
      'cancelButtonText' =>  'Cancel',
      'showCancelButton' =>  true,
      'showConfirmButton' =>  false,
]);

确认警报

此包还支持在操作中显示确认警报。

这是对之前警报确认的完全重构,以支持同一Livewire组件上的多个确认。首先,设置您的onConfirmed和onCancelled回调动作方法。当然,您可以命名任何您想要的方法。

public function confirmed()
{
    // Example code inside confirmed callback

    $this->alert(
        'success',
        'Thanks! consider giving it a star on github.'
    );
}

public function cancelled()
{
    // Example code inside cancelled callback

    $this->alert('info', 'Understood');
}

确保将确认和取消方法注册为事件监听器。

见:laravel-livewire.com/docs/2.x/events 以获取有关事件监听器的更多信息。

如果您在同一Livewire组件上有多个确认警报,您可以定义任意多的回调方法,并将其添加到事件监听器中。

protected $listeners = [
    'confirmed',
    'cancelled',
    ...
];

最后,创建一个触发确认警报的动作方法,该方法具有指向您已注册的事件监听器的onConfirmed和onCancelled回调。

public function triggerConfirm()
{
    $this->confirm('Do you love Livewire Alert?', [
        'toast' => false,
        'position' => 'center',
        'showConfirmButton' => true,
        'cancelButtonText' => Nope,
        'onConfirmed' => 'confirmed',
        // 'onConfirmed' => ['confirmed', $id], you can pass argument with array
        'onCancelled' => 'cancelled'
    ];
}