Search code examples
vue.jsbootstrap-4bootstrap-modal

Pass a parameter to a Vue Bootstrap Modal Dialog


I'm using

"bootstrap": "^4.6.0",
 "bootstrap-vue": "^2.21.2",
 "vue": "^2.6.12",

In a Vue app and I need to pass a parameter to a Bootstrap Modal Dialog. My code is:

    <input      
      v-b-modal.modal-center
      role="button"
      class="btn btn-link"
      type="button"          
      value="Edit"
      aria-disabled="false"
      style="height: 40px; width: 120px; background-color: #efefef; border: 1px solid #ccc; border-radius: 4px; cursor: pointer;"
    /> 

And I want to pass a centeredTitle to the dialog to be displayed on the header and tell it what JSON file to convert to an array to read.

     <b-modal id="modal-center" size="xl" @shown="onModalShown" @ok="onModalOk">
     <template slot="modal-title">{{ centeredTitle }}</template>

If I set the centeredTitle in code it shows fine. But I want to use the same dialog for different areas but with a different title.

if I

      onModalShown() {
      // Clear the year and data fields
      if (this.firstModalshow) {
      //  this.centeredTitle ='Education and Training',
        this.newYear = '';
        this.newData = '';
        this.$refs.yearInput.focus();
        this.tempItem = JSON.parse(JSON.stringify(this.EducationTraining));
        this.firstModalshow = false;
      }
      
    },

and uncomment the this.centeredTitle my code will not run and gives a blank screen but it does compile.

I've read Passing data to a bootstrap modal

but I can't get it to work in Vue


Solution

  • You can use a v-model instead of the v-b-modal.xxx syntax, and set it in the button's click event. This will allow you to set some properties first, which the modal can then reference.

    Your modal needs a v-model:

     <b-modal v-model="showModal" ... >
    

    Your button needs a proper click handler:

      <input      
          @click="OnEditClicked"
          role="button"
         ...
        /> 
    

    And your click handler will look like this:

        OnEditClicked() {
          this.centeredTitle ='Education and Training';
          //Other properties which the modal needs... 
          this.showModal = true;
        }