[Vuejs]-Close a bootstrap modal 5 after asynchronously submitting a form with vue js

5👍

You’ll want to entirely manage the Bootstrap modal instance in the Vue app…

1 – First, add a new data var for the modal..

data: {
        csrf: null,
        userdb: {
            first_name: '', 
            last_name: '', 
            full_name: ''}, 
        usersdb: [],
        myModal: null
    }, 

2 – And a new method (ie: showModal()) to get an instance of the Bootstrap.modal and show it…

    showModal(){
        this.myModal = new bootstrap.Modal(document.getElementById('add_userModal'), {})
        this.myModal.show()
    },

3 – Bind the new method to @click handler to show the modal (instead of using data-bs attributes)…

   <a 
        @click="showModal()"
        class="btn btn-sm btn-outline-primary px-4" 
        style="text-align:right; float:right;">
            Add
   </a>

4 – Finally, call the hide() method after the async processing…

    async createUserdb() {
          await this.getUserdb();
          await this.sendRequest(mainUrl, 'post', JSON.stringify(this.userdb));
          this.userdb.first_name = '';
          this.userdb.last_name = '';
          this.myModal.hide()
    }

Demo

Leave a comment