Abhishek
Abhishek

Reputation: 173

Modal does not closes using jQuery due to VueJS

In index.blade.php, I have this:

<div id="books_listing" class="container">
    <div class="alert alert-success" role="alert">
        <p>Book suggestions has been enabled.</p>
        <span class="status-close"><b>&times;</b></span>
    </div>
</div>

In app.js file there is this some code like this:

if (document.getElementById('books_listing')) {
    const bookForm = new Vue({
        el: '#books_listing',
        data: {
          // some data
        },

        methods: {
          // some methods
        },

        mounted: function() {
          // something  
        }
    });
}

Also, below in the same app.js file, there is this code:

$('.status-close').on('click', function(){
    console.log('here');
    let wrapper = $(this).closest('.alert');
    wrapper.fadeOut(500);
});

When I click on the close button on the modal, it does not close. What could be the possible reason?

Upvotes: 0

Views: 46

Answers (2)

Yaniv Peretz
Yaniv Peretz

Reputation: 1168

You could also move this into the mounted hook

mounted (){ $('.status-close').on('click',function({ console.log('here'); let wrapper = $(this).closest('.alert'); wrapper.fadeOut(500); }); }

so the event will be added only after vue reconstructed the html elements

Upvotes: 0

User 28
User 28

Reputation: 5168

I guess your span may be recreated by Vue then your listener will be gone. You can check the listener by right click on that element, choose Inspect. In Elements tab on you right (or bottom), choose Event Listeners tab. If it still there, may be it caused by other reasons.

By the way, I would recommend you to add event listener by using Vue instead.

<div id="books_listing" class="container">
  <div class="alert alert-success" role="alert">
    <p>Book suggestions has been enabled.</p>
    <span class="status-close" @click='close'><b>&times;</b></span>
  </div>
</div>

And

new Vue({
  el: '#books_listing',
  methods: {
    close: function () {
      let wrapper = $(this.$el).find('.alert');
      wrapper.fadeOut(500);
    }
  }
})

Upvotes: 1

Related Questions