Handle Bootstrap modal hide event in Vue JS

2019-01-24 16:44发布

Is there a decent way in Vue (2) to handle a Bootstrap (3) modal hide-event?

I found this as a JQuery way but I can't figure out how to capture this event in Vue:

$('#myModal').on('hidden.bs.modal', function () {
  // do something…
})

Adding something like v-on:hide.bs.modal="alert('hide') doesn't seem to work.

3条回答
做自己的国王
2楼-- · 2019-01-24 17:14

Bootstrap uses JQuery to trigger the custom event hidden.bs.modal so it is not easily caught by Vue (which I believe uses native events under the hood).

Since you have to have JQuery on a the page to use Bootstrap's native modal, just use JQuery to catch it. Assuming you add a ref="vuemodal" to your Bootstrap modal you can do something like this.

new Vue({
  el:"#app",
  data:{
  },
  methods:{
    doSomethingOnHidden(){
      //do something
    }
  },
  mounted(){
    $(this.$refs.vuemodal).on("hidden.bs.modal", this.doSomethingOnHidden)
  }
})

Working example.

查看更多
对你真心纯属浪费
3楼-- · 2019-01-24 17:34

Please see https://bootstrap-vue.js.org/docs/components/modal#overview There you can find event "hide" or "hidden" So you can bind this event:

<b-modal ref="someModal" @hide="doSometing">
查看更多
干净又极端
4楼-- · 2019-01-24 17:37

One option is to tie it to a variable:

data: function(){
  return {
       showModal: false
        //starts as false.  Set as true when modal opens. Set as false on close, which triggers the watch function.
},
watch: {
  showModal: function(){
    if(this.showModal == false){
     // do something
  },
}

HTML

<button id="show-modal" @click="showModal = true">Show Modal</button>

 //later if using a component
<modal v-if="showModal" @close="showModal = false">

 // or alternatively in the bootstrap structure
<div class="modal-footer">
     <button type="button" class="btn btn-default" data-dismiss="modal" @click="showModal = false">Close</button>
</div>
查看更多
登录 后发表回答