Vue Notification Tutorial: The Complete Guide

Here are the steps to create a notification in Vue using Vue-toasted.

Step 1: Install Vue.js using Vue CLI

Type the following command to install Vue CLI globally.

npm install -g @vue/cli

# or

yarn global add @vue/cli

Create a Vue.js project using the following command.

vue create vuenotify

Vue Notification Tutorial

Step 2: Install Bootstrap 4

Install Bootstrap 4 using the following command.

npm install bootstrap --save

Import the bootstrap.min.css file inside the src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

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

Step 3: Create a Form to enter the data.

For this example, I am taking two simple fields 1) Name and 2) Email.

Inside the components folder, create one component called ItemForm.vue.

// ItemForm.vue

<template>
    <div class="container">
        <div class="card">
            <div class="card-header">
                <h3>Add Item</h3>
            </div>
            <div class="card-body">
                <form @submit.prevent="addItem">
                    <div class="form-group">
                        <label>Name:</label>
                        <input type="text" class="form-control" v-model="item.name"/>
                    </div>
                    <div class="form-group">
                        <label>Price:</label>
                        <input type="text" class="form-control" v-model="item.price"/>
                    </div>
                    <div class="form-group">
                        <input type="submit" class="btn btn-primary" value="Add"/>
                    </div>
                </form>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            item: {}
        }
    },
    methods: {
        addItem() {
            
        }
    } 
}
</script>

Import ItemForm.vue component inside src >> App.vue file.

// App.vue

<template>
  <div id="app">
    <ItemForm />
  </div>
</template>

<script>
import ItemForm from './components/ItemForm.vue'

export default {
  name: 'app',
  components: {
    ItemForm
  }
}
</script>

Step 4: Install Axios To Send A Post Request.

Type the following command to install axios and vue-axios.

npm install vue-axios axios --save

Configure inside src >> main.js file.

// main.js

import Vue from 'vue'
import App from './App.vue'

import VueAxios from 'vue-axios'
import axios from 'axios'

Vue.use(VueAxios, axios)

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'

Vue.config.productionTip = false

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

We can send a POST request to the Laravel server and save the data in the database.

We can write the code inside the addItem() function of the ItemForm.vue file.

// ItemForm.vue

methods: {
   addItem() {
      let uri = 'http://notify.test/api/item/create';
      this.axios.post(uri, this.item).then((response) => {
          console.log(response.data);
      });
   }
}

I have not created Laravel API; I will do it next.

Step 5: Install Laravel 5.6.

I am using Laravel Valet, so I am installing Laravel using the following command.

laravel new notify

Set up MySQL database in the .env file.

The next step is to create a model and migration file using the following command.

php artisan make:model Item -m

Write the following schema inside a create_items_table.php file.

// create_items_table

public function up()
{
    Schema::create('items', function (Blueprint $table) {
       $table->increments('id');
       $table->string('name');
       $table->integer('price');            
       $table->timestamps();
    });
}

Type the following command.

php artisan migrate

It will create the tables in the database. I am using the MySQL database.

Step 6: Create controller and routes in an api.php.

Create the ItemController.

php artisan make:controller ItemController

Create the route inside routes >> api.php file.

// api.php

Route::post('item/create', 'ItemController@store');

Code the store function inside the ItemController.php file.

// ItemController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Item;

class ItemController extends Controller
{
    public function store(Request $request)
    {
        $item = new Item;
        $item->name = $request->get('name');
        $item->price = $request->get('price');

        $item->save();

        return response()->json(['success' =>'Your data is successfully saved'],200);
    }
}

We are still missing one thing, which is the CORS issue.

Step 7: Solve CORS Issue.

Install the package using the below command.

composer require barryvdh/laravel-cors

We need to publish the package using the following command.

php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Add the following line inside app >> Http >> Kernel.php file.

We are adding middleware on the API part so that you can write the following code.

// Kernel.php

'api' => [
      'throttle:60,1',
      'bindings',
      \Barryvdh\Cors\HandleCors::class,
],

If you have not started the Vue development server, use the following command.

npm run serve

Try to save the item in the database, and it will save successfully, and you can see it in the console.

Step 8: Install the vue-toasted library.

Install it via NPM.

npm install vue-toasted --save

Register the package inside the main.js file.

// main.js

import Toasted from 'vue-toasted'
Vue.use(Toasted, {
  duration: 1000
})

Here, I have a pass option as a time duration. You can pass the actual object that contains different properties.

You can also add the link inside the toast to cancel that toast. You can use it like this.

// main.js

Vue.use(Toasted, {
  duration: 9000,
  action : {
    text : 'Cancel',
    onClick : (e, toastObject) => {
        toastObject.goAway(0);
    }
  }
})

You can find more APIs here

You can use the toast inside the ItemForm.vue component.

// ItemForm.vue

methods: {
   addItem() {
       let uri = 'http://notify.test/api/item/create';
       this.axios.post(uri, this.item).then((response) => {
          this.$toasted.show(response.data.success);
      });
   }
}

That’s it.

1 thought on “Vue Notification Tutorial: The Complete Guide”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.