[Vue.js] Modal (Popup)


Modal (Popup) implementation via Vue.js and CSS. According to w3schools, modal is dialog box/popup window that is displayed on top of the current page. The modal here is similar to Bootstrap modal.

The following is the source code for above demo.

HTML:

<div id="vueapp">

<!-- Button trigger modal -->
<button type="button" v-on:click="isShowMyModal = true">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal" v-show="isShowMyModal">
  <h4>Modal Title</h4>
  <p>
     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas turpis
     felis, tempus sit amet sollicitudin quis, aliquet ut felis.
     Nam a malesuada sem.
  </p>
  <button type="button" v-on:click="isShowMyModal = false">Close</button>
</div>

</div>

<script src="https://unpkg.com/vue@2.3.3/dist/vue.js"></script>

We use the variable isShowMyModal and conditional rendering [2] to control the visibility of the modal.

CSS:

.modal {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  background: azure;
  padding: 1rem;
  border-radius: 1rem;
  border: 1px solid gray;
}

The CSS here is to center the modal horizontally and vertically [5].

JavaScript:

'use strict';

var app = new Vue({
  el: '#vueapp',
  data: {
    isShowMyModal: false
  }
});

Initially set isShowMyModal as false to make modal invisible in the beginning.


Tested on:

  • Chromium Version 58.0.3029.96 Built on Ubuntu , running on Ubuntu 17.04 (64-bit)
  • Vue.js 2.3.3

References:

[1]
[2]Conditional Rendering — Vue.js
[3]Event Handling — Vue.js
[4]
[5]html - How to center an element horizontally and vertically? - Stack Overflow