AppDividend
Latest Code Tutorials

Vue Notification Tutorial

923

Get real time updates directly on you device, subscribe now.

Vue Notification Tutorial is the today’s main topic. In this example, I have used Vue Toasted One of the Best Toast plugin available for VueJS. It is responsive, touch compatible, easy to use, attractive and feature rich with icons, actions, etc. In this demo, when we save any data in the database, we will display a notification saying that item has successfully saved or if we show any error then we can show it. For the backend, we use Laravel PHP Framework.

Vue Notification Tutorial

As always, we can start our project by installing the Vue.js.

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

Okay, now create a Vue.js project using the following command.

vue create vuenotify

 

Vue Notification Tutorial

Go into the project folder and open in your IDE.

cd vuenotify
code .

Step 2: Install Bootstrap 4.

Install the Bootstrap 4 using the following command.

npm install bootstrap --save

Now, import the bootstrap.min.css file inside 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 simple two fields 1) Name 2) Email.

Now, inside 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>

Now, 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

Now, configure inside src >> main.js fiie.

// 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')

Okay, now we can send a POST request to the Laravel server and save the data in the database.

Now, we can write the code inside 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);
      });
   }
}

Till now, I have not created Laravel API; I will do it in next step.

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.

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.

Related Posts
1 of 12
// 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 MySQL database.

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

Okay, now create the ItemController.

php artisan make:controller ItemController

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

// api.php

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

Now, code the store function inside 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);
    }
}

Now, still we are missing the one thing, and that is CORS issue.

Step 7: Solve CORS Issue.

Install the package using the below command.

 composer require barryvdh/laravel-cors

Now, we need to publish the package using the following command.

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

Finally, add the following line inside app >> Http >> Kernel.php file.

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

// Kernel.php

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

Okay, now if you have not started the Vue development server then start the server using the following command.

npm run serve

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

Step 8: Install vue-toasted library.

Install it via NPM.

npm install vue-toasted --save

Now, register the package inside the main.js file.

// main.js

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

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

You can also add the link inside toast so that you can 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 API on here

Now, 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);
      });
   }
}

So, finally, Vue Notification Tutorial Example From Scratch is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

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