LoginSignup
0
0

More than 3 years have passed since last update.

Vue.js で Pnotify を mixin で登録して使ってみた

Last updated at Posted at 2019-12-16

概要

アラートやメッセージの表示用のライブラリ Pnotify をVue.jsで利用したときの設定のメモ。

メッセージ表示などはどの画面からも使うような処理だったので、mixin を使ってどの画面からも呼び出せるように定義しています。

環境

  • Vue.js 2.6.10
  • Pnotify 4.0.0

ライブラリ導入

以下のコマンドでインストールできる

npm install --save pnotify

mixin を使った設定

まずは呼び出したい共通メソッドを作成。
notifyNoticeメソッドを呼び出して、通知メッセージが表示されるようにしたい。

pnotify-custom.js
import PNotify from "../node_modules/pnotify/dist/umd/PNotify.js";
import PNotifyButtons from "../node_modules/pnotify/dist/umd/PNotifyButtons.js";

export default new class {
  constructor() {
    this.defaultOptions = {
      delay: 2000,
      modules: {
        Buttons: {
          sticker: false
        }
      }
    };
  }

  notifyNotice(title, text) {
    title ? this._notify(title, text) : this._notifyNoTitle(text);
  }
  _notify(title, text, type = "notice") {
    PNotify.alert({
      type,
      title,
      text,
      delay: this.defaultOptions.delay,
      modules: this.defaultOptions.modules
    });
  }
  _notifyNoTitle(text, type = "notice") {
    PNotify.alert({
      type,
      text,
      delay: this.defaultOptions.delay,
      modules: this.defaultOptions.modules
    });
  }
}();

mixinで読み込ませるファイル

common.js
import notify from "./pnotify-custom.js";

export default {
  methods: {
    notifyNotice(title, text) {
      notify.notifyNotice(title, text);
    }
  }
};

Vueのインスタンス宣言箇所
mixinで先ほどのcommon.jsを読み込んでいる

main.js
import Vue from 'vue'
import App from './App.vue'
import "../node_modules/pnotify/dist/PNotifyBrightTheme.css";
import common from "./common.js";

Vue.mixin(common);

new Vue({
  render: h => h(App),
}).$mount('#app')

呼び出し方の例
this.notifyNotice([タイトル],[メッセージ])で呼び出せるようになっている

APP.vue
<template>
  <div id="app">
    <h1>Pnotify</h1>
    <button @click="onNotify">タイトルなし</button>
    <button @click="onNotifyTitle">タイトルあり</button>
  </div>
</template>

<script>
export default {
  name: "app",
  methods: {
    onNotify() {
      this.notifyNotice(undefined, "テスト[タイトルなし]");
    },
    onNotifyTitle() {
      this.notifyNotice("タイトル", "テスト[タイトルあり]");
    }
  }
};
</script>

<style>
</style>

表示はこんな感じで表示される
pnotify1.png
pnotify2.png

まとめ

Pnotifyは簡単にリッチなメッセージダイアログを使うことができるのでお勧めのライブラリです。

こういったメッセージの表示だけでなく、共通で使える処理の定義をまとめて登録できるので、
mixinをうまく使えると開発がかなりはかどると思う。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0