【问题标题】:Bootstrap modal doesn't work when modal defined outside of vue instance当模式在 vue 实例之外定义时,引导模式不起作用
【发布时间】:2023-03-18 11:10:02
【问题描述】:

我正在尝试从 vue 实例中打开引导模式。

如果我在函数中找到模态元素,该函数就会起作用。但是,如果我将模态元素声明为实例外部或 vue 数据对象中的变量,则模态将被破坏(出现背景但我看不到模态)。

这是我的代码:

<div id="app">
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">Modal title</h4>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

  <button class="btn btn-default" data-target="#myModal" @click="makeNormalModal">Normal Modal</button>
  <button class="btn btn-danger" data-target="#myModal" @click="makeBrokenModal">Broken Modal</button>
</div>

和javascript:

let modalElement = $('#myModal');

const app = new Vue({
  el: '#app',
  data: {
    'modal': $('#myModal')
  },
  methods: {
    makeNormalModal() {
      let element = $(event.target);
      $('#myModal').modal('show');
    },
    makeBrokenModal() {
      this.modal.modal('show');
    }
  }
});

我创建了一个jsfiddle 来显示问题。

【问题讨论】:

    标签: javascript jquery twitter-bootstrap vue.js bootstrap-modal


    【解决方案1】:

    您可以使用ref 属性:

    <div class="modal fade" id="myModal" ref="modal">
    

    然后,通过$refs属性访问它:

    $(this.$refs.modal).modal('show');
    

    更新小提琴:https://jsfiddle.net/ukmnc4gs/4/

    【讨论】:

      【解决方案2】:

      data 对象中设置 '#myModal' 而不是 $('#myModal')。

      const app = new Vue({
        el: '#app',
        data: {
          'modal': '#myModal'
        },
        methods: {
            makeBrokenModal(event) {
              $(this.modal).modal('show')
            }
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        相关资源
        最近更新 更多