便利なモーダルSweetAlert2
どうもfujiharaです。 恥ずかしながら最近まで知らなかった便利なモーダルSweetAlert2をご紹介させていただきます。
背景
フォーム実装していて通信中にモーダル出したいと思い、npmで探していたら 出会いました。Start数(12k超:2020/12/17時点)、Weekly Downloads数共に凄い数です。
使い方
いくつかご紹介します。詳しい使い方は公式サイトを参照下さい。
読み込み
<script src="sweetalert2/dist/sweetalert2.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill@8/dist/polyfill.js"></script>
もしくは npm install して importします。
一番簡単な開くは以下です。
Swal.fire('開け モーダル');

上の場合の文字はタイトルになり、タイトル、テキストの場合は2つ目の引数を設定します
Swal.fire('タイトル', 'テキストコンテンツだよ<br>確認してね');

基本はそれと Swal.close()で開いてるのを閉じてもらえば良いんですが凝った事をするときには Swal.fire(option) を使います。
Swal.fire({
icon: 'success',
title: '保存しました',
});

上記のようにiconパラメータを渡すとアイコンを表示してくれます。 iconは他にerror, info, warning, questionとあります
他のオプションでは以下をよく使いました。
Swal.fire({
icon: 'warning',
showCancelButton: true, //キャンセルボタンを表示
showCloseButton: true, //閉じるボタンを表示
allowEscapeKey: false, //エスケープキーでモーダルを閉じないようにする
allowOutsideClick: false, //黒いところクリックで閉じないように
});

次は押したボタンの状態を以下で取れます
Swal.fire({
icon: 'warning',
showCancelButton: true, //キャンセルボタンを表示
showCloseButton: true, //閉じるボタンを表示
showDenyButton: true, //NGボタンを表示
}).then((result) => {
console.log(result);
//result.isConfirmed, isDissmied, isDenied
});
上記のresultで何が押されたかによって処理を変えたりできます
Swal.fire({
icon: 'info',
title: '投稿中'
});
Swal.showLoading();
setTimeout(() => {
Swal.update({
icon: 'success',
title: '保存しました'
});
Swal.hideLoading();
},1500);

setTimeの箇所を実処理に変えてもらい、Swal.updateでコンテンツを更新できます。(更新できないプロパティーもあります)
まとめ
いかがでしたでしょうか? 詳しい箇所は本サイト見てもらればと思います。Swal.fire(), Swal.close(), Swal.update() で だいたいのことは出来ます。 preConfirm, queueもおすすめなので挑戦してみて下さい。