VueJs + VueRouter + modal. Another bike

Good day. In this article, I will analyze a method that allows you to show a modal window for our needs when changing the address. I know that there is a proprietary solution for the modal component on the official website . In addition to this, there are many other articles on Habré devoted to the topic of modal windows in VueJs (for example, this one ).



However, in my opinion, each of them has its drawbacks, for example:





Again, I cannot know everything, therefore, if you have something to say or point out, then I am open to constructive criticism. Further we will use exclusively standard functionality of the tools that we use (Vue, VueRouter, Bootstrap Modal). So, closer to the point ...



There will be people who say: "It is better to connect npm dependencies for modal than to pull all bootstrap + jquery.". Comrades, no one bothers you to adapt this whole thing to your needs and tools. The above tools are just an example of implementation.



Immediately working option .



HTML
<div id="app"> <nav> <router-link :to="{ name: 'modal' }" exact>Open Modal</router-link> </nav> <router-view></router-view> </div>
      
      







javascript
 Vue.use(VueRouter) const Modal = { template: `<div class="modal fade" tabindex="-1" role="dialog" ref="modal"> <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"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> mounted: function(){ console.log('mounted') var context = this; $(this.$refs.modal).modal('show') $(this.$refs.modal).on('hidden.bs.modal', function(){ context.$router.go(-1); }) } } const routes = [ { path: '/modal', name: 'modal', component: Modal }, ] const router = new VueRouter({ routes, }) // New VueJS instance var app = new Vue({ // CSS selector of the root DOM element el: '#app', // Inject the router into the app router, })
      
      







Actually, there is nothing complicated.



  1. When clicking on our link, our Modal component is mounted.
  2. When mounting it, we open our modal window and through this. $ Refs we track its closing.
  3. When it is closed, we programmatically return the person one step back so that our component is unmounted.


Thus, such an approach and such a structure is a good solution if you plan to have many modal windows with your own separate logic:






All Articles