[Vuejs]-Update and access alert message variable between Vue components

1๐Ÿ‘

โœ…

I would consider using an event handler instead of the global prototype.

Event.js โ€” credit to Jeffrey Way of https://laracasts.com/

class Event {
    constructor() {
        this.vue = new Vue();
    }

    fire(event, data = null) {
        this.vue.$emit(event, data);
    }

    listen(event, callback) {
        this.vue.$on(event, callback);
    }
}

export default Event;

I have outlined the basic usage below, plus I added a v-if to your alert to hide it when not in use.

app.js

import Event from './Event';
window.Event = new Event;

Alerts.vue

<template>
    <div v-if="show" class="alert alert-light alert-elevate" role="alert">
        <div class="alert-icon"><i class="flaticon-warning kt-font-brand"></i></div>
        <div class="alert-text">
            {{ alert.msg }}
        </div>
    </div>               
</template>

<script>
    export default {
        data() {
            return {
                alert: {},
                show: false,
            }
        },
        mounted() {
            // listen for a global event 
            Event.listen('show-alert',alert => {
                this.alert = alert;
                this.show = true;
            });
        },
     }
</script>

User.vue

<script>
    export default {
        mounted() {
            var datatable = this.init();
            datatable.on('kt-datatable--on-ajax-fail', function(event, data){     
                // fire a global event          
                Event.fire('show-alert',{ 
                    status: data.responseJSON.status,
                    msg: data.responseJSON.msg,
                });
            });
        },
     }
</script>
๐Ÿ‘คmatticustard

Leave a comment