Vue.js vue-toastedをインストールしてNotificationを表示する

Vue.js vue-toastedをインストールしてNotificationを表示する

Vueのライブラリvue-toastedをインストールしてNotificationを表示するまでの簡単なサンプルコードです。bootstrap-vueも少し利用。

環境

  • OS  CentOS 8.0.1905 (Core)
  • node v12.13.1
  • npm 6.13.2
  • @vue/cli 4.1.1
  • vue-toasted 1.1.27
  • bootstrap-vue 2.1.0

※CentOS8にVue.jsの環境構築はこちら

vue-toastedインストール

下記のコマンドでインストールします。

npm install vue-toasted --save

vue-sweetalert2 の利用

vue-toastedを利用するための簡単なサンプルコードを記載します。

src配下のmain.jsに下記のコードを追加します。

※bootstrap-vueも利用してます。

インストールは、npm install -S bootstrap-vueで可能です

import Toasted from 'vue-toasted';
//bootstrap-vue
import BootstrapVue from 'bootstrap-vue';
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'

Vue.use(Toasted, {
  position: 'top-center',
  duration: 3000,
  fullWidth: true,  
  type: 'success'  
})

//bootstrap-vue
Vue.use(BootstrapVue);

src/components配下にToast.vueというファイルを作成し、下記のコードを記述します。

<template>
    <div>
        <h1>vue-toasted</h1>  
        <b-button variant="outline-success" v-on:click="showToast()">Notificationを表示</b-button>    
    </div>
</template>
  
<script>    
  export default {
    methods: {
      showToast(){
          this.$toasted.show('Hello Notification')
      }
    }
  }
</script>

src配下のApp.vueも下記のように編集します。

<template>
  <div id="app">    
    <toast></toast>
    <img alt="Vue logo" src="./assets/logo.png">
  </div>
</template>
  
<script>
import Toast from './components/Toast.vue'
  
export default {
  name: 'app',
  components: {
    Toast
  }
}
</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: 260px;
  width: 60%;
}
</style>

ブラウザから http://プライベートIP:8080 にアクセスすると、 vue-toastedによりNotificationが表示されます。