首页 > 解决方案 > 在 VueJS 中显示没有 Jquery 的 Bootstrap4 模态

问题描述

我正在尝试从 VueJS 中的函数显示引导模式。我基本上是在寻找香草 JS 的方式:$('#myModal').modal("show")。BootstrapVue 有很多方法可以做到这一点,但是我目前使用的项目没有使用 bootstrapVue,只是使用标准的 bootstrap4。

//component.vue

<template>
  <div>
    <button type="button" class="btn btn-primary">My Modal</button>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
          ...
        </div>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  methods: {
    buttonClick() {
      // Need to display modal in here
      //$('#myModal').modal("show")
    }
  }
};
</script>

标签: javascripttwitter-bootstrapvue.jsbootstrap-4bootstrap-modal

解决方案


当您希望引导模态如何使用 jquery 时,您会发现他们向模态添加了一个显示类并将模态的样式从更改style="display: none"style="display:block"

和一个 div<div class="modal-backdrop fade show"></div>附加到正文,这个 div 是模态后面的黑色覆盖背景

所以要做到这一点,你可以做这样的事情:

<template>
  <div>
    <button type="button" class="btn btn-primary" @click="toggleModal">My Modal</button>
    <div
      ref="modal"
      class="modal fade"
      :class="{show, 'd-block': active}"
      tabindex="-1"
      role="dialog"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Modal title</h5>
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
              @click="toggleModal"
            >
              <span aria-hidden="true">&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <p>Modal body text goes here.</p>
          </div>
        </div>
      </div>
    </div>
    <div v-if="active" class="modal-backdrop fade show"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      active: false,
      show: false
    };
  },
  methods: {
    /**
     * when clicking on button in bootstrap
     * the modal style set to display and after that a show class add to modal
     * so to do that we will show modal-backdrop and set modal display to block
     * then after that we will add show class to the modal and we will use setTimeout
     * to add show class because we want show class to add after the modal-backdrop show and modal display change
     * to make modal animation work
     *
     */
    toggleModal() {
      const body = document.querySelector("body");
      this.active = !this.active;
      this.active
        ? body.classList.add("modal-open")
        : body.classList.remove("modal-open");
      setTimeout(() => (this.show = !this.show), 10);
    }
  }
};
</script>

代码沙盒演示

希望这可以帮到你


推荐阅读