【问题标题】:Vue.js open modal by click of a buttonVue.js 通过单击按钮打开模式
【发布时间】:2018-10-29 21:10:42
【问题描述】:

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

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 来显示模态,像这样:

&lt;button class="btn btn-info" data-toggle="modal" data-target="#exampleModal"&gt;show modal&lt;/button&gt;

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

【问题讨论】:

  • 但是您想在点击时显示哪个组件? userInfoModal 还是 exampleModal ?
  • 我想在点击时显示 exampleModal。谢谢,我已经编辑了问题

标签: javascript vue.js vuejs2 bootstrap-4


【解决方案1】:

根据您的 sn-p,您使用的是经典的 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

【讨论】:

  • 这不适用于Nuxtjs。我在components 目录中创建了BootstrapVue 模态。我已将其添加到我的 pages 现在,当我尝试重新启动服务器时,我收到错误 '$' is not defined
【解决方案2】:

如果没有 jQuery,你可以像这样在“method:”块上创建一个函数:

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

【讨论】:

  • 这是最好的答案
  • 如果我不使用 BootstrapVue,只使用标准 bootstrap4,你会怎么做
猜你喜欢
  • 2017-12-12
  • 2014-11-06
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多