LoginSignup
14
8

More than 3 years have passed since last update.

【Vue.js】エラーの表示を簡単に実装してみる ~ vue-toasted ~

Posted at

概要

本記事では、Vue.jsで使える便利なNotificationライブラリである vue-toastedについてまとめていきます。

vue-toasted って?

vue-toasted とは、概要にも記述した通り、Vue.jsで使えるNotificationライブラリです。
実装自体も簡単で、3分あれば実装できてしまうとても便利なものです。
トーストでお知らせを表示させたい時にぜひ使ってみてください!

公式ページ : https://www.npmjs.com/package/vue-toasted

環境

Vue.js 2.9.6

インストール

yarn、npm、CDNののいずれかでインストールしてください。

yarn

yarn add vue-toasted

npm

npm install vue-toasted --save

CDN

index.html
<script src="https://unpkg.com/vue-toasted"></script>

実装方法

  1. vue-toastedを読み込む
main.js
import Vue from 'vue'
import App from './App.vue'
import Toasted from 'vue-toasted';

Vue.use(Toasted);

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

※CDNの場合はimportの記述は必要ありません。

2.Vueコンポーネントで呼び出す

App.vue
<template>
  <div id="app">
    <button @click="btnClick">クリック</button>
  </div>
</template>

<script>
export default {
  methods: {
    btnClick() {
      this.errToast("エラーです!");
    },
    errToast:function(msg){
      // main.jsで読み込んだので this.$toasted で呼び出せる
      this.$toasted.error(msg);
    },
  }
}
</script>

<style>
.toasted-container .toasted {
  /* スタイルを修正することもできます */
}
</style>

これで実装は完了です。
今回はエラーの表示の時のトーストを実装したため、赤色のトーストが表示されたと思います。
エラー以外にも、オプションを設定すれば様々なトーストを実装することができます。

応用編

オプション

index.js
import Vue from 'vue'
import App from './App.vue'
import Toasted from 'vue-toasted';

// オプション設定
// 今回はポジション・表示されてから消えるまでの時間・横幅についてのオプション追加
var options = {
  position: 'top-center',
  duration: 2000,
  fullWidth: true,
}

Vue.use(Toasted, options);

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

このようにオプションを渡してあげることによって、思い通りのトーストを簡単に実装することができます。
下記URLから、ぽちぽち操作して目で見ながら理想のトーストを作っていくこともできるのでおすすめです!
https://shakee93.github.io/vue-toasted/

14
8
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
14
8