Vue.js通过单击按钮打开模态

时间:2018-05-19 17:54:12

标签: javascript vue.js vuejs2 bootstrap-4

如何使用按钮在其他组件中显示模态?例如,我有以下组件:

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>

如何从exampleModal.vue中显示模态?我知道我可以 使用data-toggle和data-target来显示模态,如下所示:

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

但有没有办法通过使用方法“showModal”显示模态?

2 个答案:

答案 0 :(得分:2)

根据你的片段,你使用的是经典的Bootstrap模式。在这种情况下,您只需要使用data-toggledata-target属性:

<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>

修改

我误解了这个问题所以我编辑了我的答案。

可以使用自定义方法打开模态。您只需使用refs找到元素“#exampleModal”,然后使用引导方法(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

答案 1 :(得分:0)

没有jQuery,您可以在“ method:”块上创建一个函数,如下所示:

$i