单击按钮即可打开Vue.js模式

use*_*119 5 javascript vue.js bootstrap-4 vuejs2

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

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

如何从exampleModal.vue显示模态?我知道我可以使用数据切换和数据目标来显示模式,如下所示:

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

但是,有没有办法使用“ showModal”方法来显示模态?

Sov*_*ina 6

根据您的代码段,您正在使用经典的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>
Run Code Online (Sandbox Code Playgroud)

编辑

我看错了问题,所以我编辑了答案。

可以使用自定义方法打开模式。您只需要通过使用查找元素“ #exampleModal” refs,然后使用引导程序方法(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>
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

小提琴的例子


Luc*_*tos 6

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

openEditModal(data){
  // <handle with your data>
  this.$root.$emit("bv::show::modal", "your-modal-id");
}
Run Code Online (Sandbox Code Playgroud)

  • 如果我不使用 BootstrapVue,只使用标准 bootstrap4,你会怎么做? (4认同)
  • 这是最好的答案 (2认同)