Open bootstrap modal with vue.js 2.0

78,814

Solution 1

My code is based on the Michael Tranchida's answer.

Bootstrap 3 html:

<div id="app">
  <div v-if="showModal">
    <transition name="modal">
      <div class="modal-mask">
        <div class="modal-wrapper">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <button type="button" class="close" @click="showModal=false">
                  <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Modal title</h4>
              </div>
              <div class="modal-body">
                modal body
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
  <button id="show-modal" @click="showModal = true">Show Modal</button>
</div>

Bootstrap 4 html:

<div id="app">
  <div v-if="showModal">
    <transition name="modal">
      <div class="modal-mask">
        <div class="modal-wrapper">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true" @click="showModal = false">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <p>Modal body text goes here.</p>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" @click="showModal = false">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
  <button @click="showModal = true">Click</button>
</div>

js:

new Vue({
  el: '#app',
  data: {
    showModal: false
  }
})

css:

.modal-mask {
  position: fixed;
  z-index: 9998;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, .5);
  display: table;
  transition: opacity .3s ease;
}

.modal-wrapper {
  display: table-cell;
  vertical-align: middle;
}

And in jsfiddle

Solution 2

Tried to write a code that using VueJS transitions to operate native Bootsrap animations.

HTML:

    <div id="exampleModal">
      <!-- Button trigger modal-->
      <button class="btn btn-primary m-5" type="button" @click="showModal = !showModal">Launch demo modal</button>
      <!-- Modal-->
      <transition @enter="startTransitionModal" @after-enter="endTransitionModal" @before-leave="endTransitionModal" @after-leave="startTransitionModal">
        <div class="modal fade" v-if="showModal" ref="modal">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button class="close" type="button" @click="showModal = !showModal"><span aria-hidden="true">×</span></button>
              </div>
              <div class="modal-body">...</div>
              <div class="modal-footer">
                <button class="btn btn-secondary" @click="showModal = !showModal">Close</button>
                <button class="btn btn-primary" type="button">Save changes</button>
              </div>
            </div>
          </div>
        </div>
      </transition>
      <div class="modal-backdrop fade d-none" ref="backdrop"></div>
    </div>

Vue.JS:

    var vm = new Vue({
      el: "#exampleModal",
      data: {
        showModal: false,
      },
      methods: {
        startTransitionModal() {
          vm.$refs.backdrop.classList.toggle("d-block");
          vm.$refs.modal.classList.toggle("d-block");
        },
        endTransitionModal() {
          vm.$refs.backdrop.classList.toggle("show");
          vm.$refs.modal.classList.toggle("show");
        }
      }
    });

Example on Codepen if you are not familiar with Pug click View compiled HTML on a dropdown window in HTML section.

This is the basic example of how Modals works in Bootstrap. I'll appreciate if anyone will adopt it for general purposes.

Have a great code 🦀!

Solution 3

I did an amalgam of the Vue.js Modal example and the Bootstrap 3.* live demo.

Basically, I used the Vue.js modal example but replaced (sorta) the Vue.js "html" part with the bootstrap modal html markup, save one thing (I think). I had to strip the outer div from the bootstrap 3, then it just worked, voila!

So the relevant code is regarding bootstrap. Just strip the outer div from the bootstrap markup and it should work. So...

ugh, a site for developers and i can't easily paste in code? This has been a serious continuing problem for me. Am i the only one? Based on history, I'm prolly an idiot and there's an easy way to paste in code, please advise. Every time i try, it's a horrible hack of formatting, at best. i'll provide a sample jsfiddle of how i did it if requested.

Solution 4

Here's the Vue way to open a Bootstrap modal..

Bootstrap 5 (2022)

Now that Bootstrap 5 no longer requires jQuery, it's easy to use the Bootstrap modal component modularly. You can simply use the data-bs attributes, or create a Vue wrapper component like this...

<bs-modal id="theModal">
        <button class="btn btn-info" slot="trigger"> Bootstrap modal </button>
        <div slot="target" class="modal" tabindex="-1">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">Modal title</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p>Modal body text goes here.</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                            <button type="button" class="btn btn-primary">Save changes</button>
                        </div>
                    </div>
                </div>
        </div>
</bs-modal>


const { Modal } = bootstrap

const modal = Vue.component('bsModal', {
    template: `
        <div>
            <slot name="trigger"></slot>
            <slot name="target"></slot>
        </div>
    `,
    mounted() {
        var trigger = this.$slots['trigger'][0].elm
        var target = this.$slots['target'][0].elm
        trigger.addEventListener('click',()=>{
            var theModal = new Modal(target, {})
            theModal.show()
        })
    },
})

Bootstrap 5 Modal in Vue Demo

Bootstrap 4

Bootstrap 4 JS components require jQuery, but it's not necessary (or desirable) to use jQuery in Vue components. Instead manipulate the DOM using Vue...

   <a href="#reject" role="button" class="btn btn-primary" @click="toggle()">Launch modal</a>
   <div :class="modalClasses" class="fade" id="reject" role="dialog">
       <div class="modal-dialog">
             <div class="modal-content">
                  <div class="modal-header">
                    <h4 class="modal-title">Modal</h4>
                    <button type="button" class="close" @click="toggle()">&times;</button>
                  </div>
                  <div class="modal-body"> ... </div>
              </div>
       </div>
   </div>

var vm = new Vue({
  el: '#app',
  data () {
    return {
        modalClasses: ['modal','fade'],
    }
  },
  methods: {
    toggle() {
        document.body.className += ' modal-open'
        let modalClasses = this.modalClasses
    
        if (modalClasses.indexOf('d-block') > -1) {
            modalClasses.pop()
            modalClasses.pop()
    
            //hide backdrop
            let backdrop = document.querySelector('.modal-backdrop')
            document.body.removeChild(backdrop)
        }
        else {
            modalClasses.push('d-block')
            modalClasses.push('show')
    
            //show backdrop
            let backdrop = document.createElement('div')
            backdrop.classList = "modal-backdrop fade show"
            document.body.appendChild(backdrop)
        }
    }
  }
})

Bootstrap 4 Vue Modal Demo

Solution 5

Using the $nextTick() function worked for me. It just waits until Vue has updated the DOM and then shows the modal:

HTML

<div v-if="is_modal_visible" id="modal" class="modal fade">...</div>

JS

{
  data: {
    isModalVisible: false,
  },
  methods: {
    showModal() {
      this.isModalVisible = true;
      this.$nextTick(() => {
        $('#modal').modal('show');
      });
    }
  },
}
Share:
78,814
Trung Tran
Author by

Trung Tran

Updated on June 17, 2021

Comments

  • Trung Tran
    Trung Tran almost 3 years

    Does anyone know how to open a bootstrap modal with vue 2.0? Before vue.js I would simply open the modal by using jQuery: $('#myModal').modal('show');

    However, is there a proper way I should do this in Vue?

    Thank you.

  • Felipe Thomas
    Felipe Thomas about 5 years
    How to overflow-y with BS 3?
  • Cristian Porto
    Cristian Porto over 4 years
    You can post code with indenting, backticks or embedding a fiddle. Here is a detailed reference. The question editor has buttons to insert code too.
  • yahermann
    yahermann over 4 years
    To prevent form from submitting, add preventDefault() to button. <button @click.prevent="showModal = true">Click</button>. To prevent flickering of modal on load, add v-cloak: <div v-if="showModal" v-cloak> and within css: [v-cloak] { display:none; }
  • Vlad
    Vlad about 4 years
    Excellent answer. Just to add, for Bootstrap 4, the key is NOT having the class "modal" div added at all. It pulls the dialog off screen and seems to require JS to open it, which of course could be done in mounted() event. Still, it seems too complicated an approach, and I find THIS solution cleaner. One, in fact can skip everything until <div class="modal-dialog" ...> since we are displaying the component ourselves, with Vue. Unless, of course you want some fancy transitions.
  • rakensi
    rakensi about 4 years
    Your answer attracted a down-vote, but no reason was given. I use your answer in a web-application, and I have the impression that opening dialogs like this causes a memory leak. But I have no solid evidence for that. It would be great if someone could explain why this answer does not work.
  • Joe C.
    Joe C. about 4 years
    Just using the programmatic API will not cause a memory leak. The call here will only show an existing modal attached to an element. However, if it's not working in code you're using, chances are you're encountering issues where the DOM element that the modal was originally attached to no longer exists due to a Vue re-render. That's the main issue with using traditional Javascript and jQuery-based libraries: They rely on the DOM elements not changing all the time, which is an invalid assumption with reactive frameworks like Vue.
  • Andrew Koster
    Andrew Koster about 4 years
    It would be nice if Bootstrap adapted to reactive frameworks, it's not like Vue is the only one or even the most popular one.
  • Mark Brown
    Mark Brown over 3 years
    This likely got a down vote because it's jquery not vue.
  • Andrew Koster
    Andrew Koster over 3 years
    Bootstrap 4 is implemented with jQuery. That jQuery code is directly from the Bootstrap documentation.
  • Indiana Kernick
    Indiana Kernick over 3 years
    I tried this and it doesn't seem to be playing the transition animation. I also tried the example from the Vue 3 docs and it doesn't play the transition animation either. I'm not very experienced with CSS transitions. I looked into importing the Bootstrap JavaScript module (along with jQuery and Popper) and ugh, so much bloat for something so simple. (I could almost say that about Vue actually. Almost...) Screw it! The dialog will appear and disappear instantly.
  • Indiana Kernick
    Indiana Kernick over 3 years
    Ok I worked it out. You actually need to define a transition when using the <transition> element (which sounds pretty obvious now that I think about it!). See the docs. You also need to put the v-if inside the <transition>.
  • Emmanuel Neni
    Emmanuel Neni almost 2 years
    Uncaught TypeRrror: bash Uncaught TypeError: Cannot read properties of undefined (reading 'classList') The modal has a v-if which means it will not exist once showModal is set to false Solution: Only call toggle on the modal ref if the ref is found js startTransitionModal() { this.$refs.backdrop.classList.toggle("d-block"); if (this.$refs.modal) this.$refs.modal.classList.toggle("d-block"); }, endTransitionModal() { this.$refs.backdrop.classList.toggle("show"); if (this.$refs.modal) this.$refs.modal.classList.toggle("show"); }, Thank you.
  • Fernando Torres
    Fernando Torres almost 2 years
    Only this solution worked for me, tu!