vue-swalとは
「vue-swal」は、美しいアラートを実装するライブラリです。
ダイアログのステータスやボタン、テキスト入力をサポートしています。
シンプルな実装ながら、CSSをカスタマイズすること無く綺麗なアラートを実装できます。
vue-swalの導入方法
以下のnpm、yarn、CDNを使ってインストールします。
- npm
npm install vue-swal
- yarn
yarn add vue-swal
- CDN
CDN
<script src="https://unpkg.com/vue-swal"></script>
導入手順
1.ライブラリの取り込み
import Vue from "vue";
import VueSwal from "vue-swal";
Vue.use(VueSwal);
2.メソッドを設定
export default {
methods: {
postItem() {
const id = firebase.firestore().collection("posts").doc().id;
firebase
.firestore()
.collection("posts")
.add({
title: this.title,
description: this.description,
genre: this.genre,
time: firebase.firestore.FieldValue.serverTimestamp(),
id: id,
});
this.$swal({
title: "内容確認",
text: "この内容で投稿しますか?",
icon: "info",
buttons: true,
dangerMode: true,
}).then((willDelete) => {
if (willDelete) {
this.$swal("投稿しました。", {
icon: "success",
});
this.$router.go({ path: "/board", force: true });
} else {
this.$swal("キャンセルしました。");
}
});
},
},
}
「vue-swal」は4つのステータスをサポートしています。
- warning
- error
- success
- info
記述方法は下記を参照。
.then((willDelete) => {
if (willDelete) {
this.$swal("投稿しました。", { //投稿された際のメッセージ
icon: "success", //ここに記述。
});
this.$router.go({ path: "/board", force: true }); //投稿された場合、ページをリロード
} else {
this.$swal("キャンセルしました。"); //上記以外の場合のメッセージ
}
});
3. テンプレートを準備
<button class="post-btn" @click.prevent="postItem">投稿</button>
上記を追記することでメニュー外をクリックしたら閉じるようになったかと思います。