Vue.js vue-sweetalert2をインストールしてalertを表示する
- 2020.01.20
- Vue.js
- vue-sweetalert2, Vue.js

Vueのライブラリvue-sweetalert2をインストールしてalertを表示するまでの簡単なサンプルコードです。 bootstrap-vueも少し利用してます。
環境
- OS CentOS 8.0.1905 (Core)
- node v12.13.1
- npm 6.13.2
- @vue/cli 4.1.1
- vue-sweetalert2 2.1.5
- bootstrap-vue 2.1.0
※CentOS8にVue.jsの環境構築はこちら
vue-sweetalert2インストール
下記のコマンドで実行します。
1 |
npm install -S vue-sweetalert2 |
ついでにbootstrap-vueもインストールしておきます。
1 |
npm install -S bootstrap-vue |
vue-sweetalert2 の利用
vue-sweetalert2を利用するための簡単なサンプルコードを記載します。
src配下のmain.jsに下記のコードを追加します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import VueSweetalert2 from 'vue-sweetalert2'; import BootstrapVue from 'bootstrap-vue' import 'sweetalert2/dist/sweetalert2.min.css'; import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' //ボタンの色をグローバルに設定 const options = { confirmButtonColor: '#41b882', cancelButtonColor: '#ff7674', }; Vue.use(VueSweetalert2, options); Vue.use(BootstrapVue) |
インストール時にデフォルトであるsrc/components配下のHelloWorld.vueを下記のように編集します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<template> <div class="container"> <b-button variant="success" @click="showAlert">click</b-button> </div> </template> <script> export default { methods: { showAlert() { this.$swal({ title: 'よろしいですか?', text: "よろしければOKボタンを押してください", type: 'warning', showCancelButton: true, confirmButtonText: 'OK' }).then((result) => { if (result.value) { this.$swal( 'OK!', '成功しました.', 'success' ) } }); }, }, }; </script> |
src配下の CSSを少し追加しただけで App.vueはデフォルトのままです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<template> <div id="app"> <img alt="Vue logo" src="./assets/logo.png"> <HelloWorld msg="Welcome to Your Vue.js App"/> </div> </template> <script> import HelloWorld from './components/HelloWorld.vue' export default { name: 'app', components: { HelloWorld } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; margin: 0 auto; text-align: center; color: #2c3e50; margin-top: 60px; width: 60%; } </style> |
ブラウザから http://プライベートIP:8080 にアクセスすると、 vue-sweetalert2によりclickボタンをクリックすると、アラートが表示されます。

-
前の記事
Vue.js ant-design-vueを使用してみる 2020.01.19
-
次の記事
React.js コンポーネントの簡単な使い方 2020.01.20
コメントを書く