'vue-js-modal not showing in HTML

I checked the demo and confirmed it does work in the demo way. But I need to use the components in HTML but not in webpack-ed a modal.vue template. So I wrote the following:


<body>

        <div id="app">
            <modal name="test">
                test
            </modal>
        </div>

    <script src="{% static 'js/tmpdev.bundle.js' %}" type="text/javascript"></script>
    
    <script>

    Vue.use(VueJsModal, {
        dialog: true,
        dynamicDefaults: {
            draggable: true
        }
    })

    new Vue({
        el: '#app',
        components: {
        },
        data() {
            return {
            };
        },
        mounted() {
            window.addEventListener('keydown', (e) => {
                if (e.key == 'Escape') {
                    this.toggle();
                }
            });
            this.$modal.show('test');
        },
        methods: {
            toggle() {
                this.$modal.show('test');
            }
        },
        filters: {
        },
    });

    </script>

</body>

The above should display the modal window on the screen immediately when I reloaded the tab or additionally when I pressed "esc" key. But for some reason this doesn't show the modal. The console log has no error on it, I can see <div id="modals-container"></div> on the HTML source, the this.$modal.show('test'); part is executed without an error. So I have no clue now. What is wrong with the code above? Thanks.



Solution 1:[1]

You should add Escape key EventListener code in the created life cycle hook.

window.addEventListener('keydown', this.toggle);

In methods object :

toggle(event) {
  if (event.keyCode === 27) {
    this.$modal.show('test');
    console.log('esc key pressed');
  }
}

Once you done with the requirement, You can destroy this event to prevent memory leaks.

destroyed: function() {
  document.removeEventListener('keydown', this.toggle);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rohìt Jíndal