Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js open modal by click of a button

How to use a button to show the modal in other components? For example, I have the following components:

info.vue

<template>
  <div class="container">
    <button class="btn btn-info" @click="showModal">show modal</button>
    <example-modal></example-modal>
  </div>
</template>

<script>
import exampleModal from './exampleModal.vue'
export default {
  methods: {
    showModal () {
      // how to show the modal
    }
  },
  components:{
    "example-modal":exampleModal
  }
}
</script>

exampleModal.vue

<template>
    <!-- Modal -->
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            hihi
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
        </div>
    </div>
    </div>
</template>

How to show the modal from exampleModal.vue? I know that I can use data-toggle and data-target to show the modal, like this:

<button class="btn btn-info" data-toggle="modal" data-target="#exampleModal">show modal</button>

But is there any way to show the modal by using the method "showModal"?

like image 385
user3717119 Avatar asked May 19 '18 17:05

user3717119


1 Answers

According to your snippet, you're using a classic Bootstrap modal. You just need to use data-toggle and data-target attributes in that case:

<div id="app">
  <div class="container">
    <button class="btn btn-info" data-toggle="modal" data-target="#exampleModal">show modal</button>
    <example-modal></example-modal>
  </div>
</div>

Edit

I misread the question so i edit my answer.

It's possible to open the modal with a custom method. You just need to find the element "#exampleModal" by using refs and then open the modal with a bootstrap method (Bootstrap Programmatic API)

<div id="app">
  <div class="container">
    <button class="btn btn-info" @click="showModal">show modal</button>
    <example-modal ref="modal"></example-modal>
  </div>
</div>
methods: {
  showModal() {
    let element = this.$refs.modal.$el
    $(element).modal('show')
  }
}

Fiddle example

like image 93
Sovalina Avatar answered Sep 29 '22 15:09

Sovalina