How To Build A Super Light Flash Notification Component In VueJS And Laravel

profile picture

How To Build A Super Light Flash Notification Component In VueJS And Laravel

Today another tutorial where we are going to build a flash notification system for your VueJS application. It works both with Single Page Application (vue-router) and with classic Laravel app with a bit of VueJS components πŸ˜‰

This is almost an all-in-one component that will work directly after installation. The only thing you'll need to do is to implement the different level css classes. The notification will fade in on your screen and disappear after 10 seconds.

First, a little demo for you folks.

Alright let's start.

The Notification component

Create a new notification component and register it globally.

// app.js
Vue.component('notification', require('./components/Notification.vue'));
// Notification.vue
<template>
    <div class="flash notification" :class="[
        levelClass, isOpen ? isVisibleClass : ''
    ]">
        <button class="delete" @click="isOpen = false"></button>
        {{ messageText }}
    </div>
</template>

<script>
export default {
    props: ['level', 'message'],
    data() {
        return {
            isOpen: false,
            isVisibleClass: 'is-visible',
            closeAfter: 10000,// 10 seconds, you can change that
            levelClass: null,
            messageText: null
        }
    },
    created() {
        if (this.level) {
            this.levelClass = 'is-' + this.level;
        }
        if (this.message) {
            this.messageText = this.message;
            this.flash();
        }
        let self = this;
        window.events.$on(
            'flash', data => self.flash(data)
        );
    },
    methods: {
        flash(data) {
            if (data) {
                this.messageText = data.message;
                this.levelClass = 'is-' + data.level;
            }

            let self = this;

            setTimeout(() => {
                self.isOpen = true;
            }, 100);

            this.hide();
        },
        hide() {
            let self = this;

            setTimeout(() => {
                self.isOpen = false;
            }, self.closeAfter);
        }
    },
}
</script>

<style lang="scss" scoped>
.flash.notification {
    z-index: 99999999999;
    position: fixed;
    bottom: 30px;
    right: 30px;
    opacity: 0;
    transform: translate(100%);
    transition: all 0.8s ease-in-out;
    &.is-visible {
        transform: translate(0);
        opacity: 1;
    }
}
</style>

The Global Helper

Register a global helper to trigger your notification from any vuejs component

// app.js
window.events = new Vue();

window.flash = function (message, level = 'success') {
    window.events.$emit('flash', { message, level });
};

The default level class of your flash notification will be "is-success", but you can of course do whatever you like better.

Inject the component in your layout

This next and final part will differ depending if you are building a SPA or if you are injecting VueJS components inside a Laravel-server-rendered application.

In your layout file:

<!-- layout.blade.php -->

@if(session('flash_notification'))

    @foreach (session('flash_notification', collect())->toArray() as $message)
        <notification level="{{ $message['level'] }}" message="{!! $message['message'] !!}"></notification>
    @endforeach

    {{ session()->forget('flash_notification') }}

@endif

<notification></notification>

If you're building a SPA, you only need the <notification></notification> part.

How to use

First, make sure that you implemented some CSS styles for the different level classes:

.is-success { background-color: green; }
.is-danger { background-color: red; }
...

If you're working with bulma then you don't have to do anything as the css is already adapted πŸ‘

From your VueJS Component

// Error
flash('There was an error, please try again!', 'danger');

// Success
flash('Your profile was successfully updated!', 'success');

// Warning
flash('Do not forget to change your password once in a while.', 'warning');

// etc.

From your Laravel Back End

If you're using laracasts/flash

// Error
flash('There was an error, please try again!', 'danger');

// Success
flash('Your profile was successfully updated!', 'success');

// Warning
flash('Do not forget to change your password once in a while.', 'warning');

Exactly the same thing πŸ˜„

And if you're using the default flash notification feature of Laravel then you know what to do !

vuejs
flash
notification

about me

profile picture

I consider myself as an IT Business Artisan. Or Consultant CTO. I'm a self-taught Web Developper, coach and teacher. My main work is helping and guiding digital startups.

more about me

follow me

newsletter

A weekly email with the latests articles

support my work

Start trading on binance
  • BTC

    BTC

    18SY81ejLGFuJ9KMWQu5zPrDGuR5rDiauM

  • ETH

    ETH

    0x519e0eaa9bc83018bb306880548b79fc0794cd08

  • Monero

    XMR

    895bSneY4eoZjsr2hN2CAALkUrMExHEV5Pbg8TJb6ejnMLN7js1gLAXQySqbSbfzjWHQpQhQpvFtojbkdZQZmM9qCFz7BXU

2024 © My Dynamic Production SRL All rights Reserved.