[Vuejs]-How to create Vue.Js component dynamically – modal messagebox

0👍

Admittedly, this is not exactly the solution I was looking for. Still, it solves my problem.

(function () {
    'use strict';
    Vue.component('message-box', {
        props: {
        },
        data: function () {
            return {
                messages: [],
                actualMessage: {},
                visible: false
            };
        },
        template:
            `<b-modal centered v-model="visible">
                <template slot="modal-header" v-if="actualMessage">
                     {{actualMessage.messageTitle}}
                </template>
                <div class="d-block text-center" v-if="actualMessage">
                    {{actualMessage.messageBody}}
                </div>
                <template slot="modal-footer">
                    <b-button class="mt-3" variant="outline-info" block v-on:click="hideModal()">Ok</b-button>         
        </template>
        </b-modal>`,
        created: function () {
            this.$root.$on('show-message', this.showMessage);
        },
        beforeDestroy: function () {
            EventBus.$off('show-message', this.showMessage);
        },
        methods: {
            showModal() {
                this.actualMessage = this.messages[0];
                this.visible = true;
            },
            hideModal() {
                this.visible = false;
                this.messages.splice(0, 1);
                if (this.messages.length > 0) {
                    var vm = this;
                    setTimeout(function () { vm.showModal(); }, 500);
                }
            },
            showMessage: function (title, message) {
                this.messages.push({ messageTitle: title, messageBody: message });
                if (!this.visible)
                    this.showModal();
            }
        }
    });
})();

Leave a comment