search

Home  >  Q&A  >  body text

Programmatically render multiple modal boxes in the same component in Vue

<p>In my component, I have three popup modals with different content. By clicking on a specific button, I need to open the corresponding popup modal. </p> <p>This is what I'm doing <strong>For button 1 -</strong></p> <pre class="brush:php;toolbar:false;"><s-button type="button" class="bl_btn" @click="onClickProdOpen"> Product Details </s-button></pre> <p><strong>For this modal 1 will be </strong></p> <pre class="brush:php;toolbar:false;"><s-modal v-model="isShowPopup1" :title="$t('LBL_PROD_CONT')" <my-component-one :pageId ="this.$options.name" :popupDefaultTab="popupOpenDefaultTab" :onClickClose="onClickclose" /></pre> <p><strong>Here is a button click method. Click events for multiple different modal boxes like this. </strong></p> <pre class="brush:php;toolbar:false;">methods: { onClickProdOpen() { this.isShowPopup1 = true; this.popupOpenDefaultTab = 0; } }</pre> <p><s-modal is the custom modal box part, the content will be different. So, I repeated this modal code and just changed the content, i.e. passed different child components (MyComponentOne, MyComponentTwo...). </p> <p>So, how can I use a switch case statement to avoid repeating the modal box code multiple times and just change the inner content component? Any suggestions will be helpful. </p>
P粉627027031P粉627027031460 days ago576

reply all(1)I'll reply

  • P粉256487077

    P粉2564870772023-08-29 09:56:52

    One option is to put the state of each modal in an object. This way, you don't need to add a data attribute to each modal.

    If the content inside the modal is similar enough, you can use v-for, using the index as the key in the same way.

    <b-modal v-model="modal_states[1]">模态框1</b-modal>
        <b-button @click="openModal(1)">打开1</b-button>
        
        <b-modal v-model="modal_states[2]">模态框2</b-modal>
        <b-button @click="openModal(2)">打开2</b-button>
        
        <b-modal v-model="modal_states[3]">模态框3</b-modal>
        <b-button @click="openModal(3)">打开3</b-button>
    data: {
        modal_states: {},
      },
      methods: {
        openModal(index){
          this.modal_states = {[index.toString()]:true}
        }
      },

    https://codepen.io/timfranklin/pen/abWEwLy?editors=1111

    reply
    0
  • Cancelreply