0

I am trying to open up a bootstrap modal from within a vue instance.

The function works if I find the modal element within the function. However, if I declare the modal element as a variable either outside the instance or in the vue data object the modal is broken (the backdrop appears but I can't see the modal).

Here is my code:

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

and the 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');
    }
  }
});

I have created a jsfiddle to show the issue.

2 Answers 2

1

You could use the ref attribute:

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

Then, access it via $refs property:

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

Updated fiddle: https://jsfiddle.net/ukmnc4gs/4/

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of $('#myModal') set '#myModal' inside your data object.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.