Search code examples
htmlvue.jsbootstrap-vue

How to separately collapse dynamic accordions inside a vue js v-for?


I need to separately collapse accordions created inside a vue js v-for. I know that something like Id which can be used to separately identify the accordion will solve this. But don't know where to give this dynamic id?

Here is my HTML

<div role="tablist">
<div v-for="item in productFormData" v-bind:key="item.id">
  <b-card no-body class="mb-1">
    <b-card-header header-tag="header" class="p-1" role="tab">
       <b-button block v-b-toggle.accordion-productdetails variant="info">Product Details</b-button>       
    </b-card-header>

    <b-collapse
      id="accordion-productdetails"
      visible
      accordion="productdetails-accordion"
      role="tabpanel"
    >

      <div class="container-fluid">
        <div class="row">
          <div class="col-sm-4">
            <span style="font-size:13px;font-weight:bold;">Name</span>
            <div>
              <span id="spnCustomerName">{{item.name}}</span>
            </div>
          </div>


          </div>
    </b-collapse>
  </b-card>
</div>


Solution

  • To add a dynamic id to it you need to add index to the for loop so every time you use the index to identify the specific accordion like this, or you can use your item.id but i don't know the content of it:

    CODEPEN : https://codepen.io/emkeythekeyem/pen/WNbqeyM?editors=1010

    <div role="tablist">
    <div v-for="(item,index) in productFormData" v-bind:key="item.id">
      <b-card no-body class="mb-1">
        <b-card-header header-tag="header" class="p-1" role="tab">
           <b-button block v-b-toggle="'accordion-productdetails'+index" variant="info">Product Details</b-button>       
        </b-card-header>
    
        <b-collapse
          :id="'accordion-productdetails'+index"
          visible
          :accordion="'productdetails-accordion'+index"
          role="tabpanel"
        >
    
          <div class="container-fluid">
            <div class="row">
              <div class="col-sm-4">
                <span style="font-size:13px;font-weight:bold;">Name</span>
                <div>
                  <span id="spnCustomerName">{{item.name}}</span>
                </div>
              </div>
    
    
              </div>
        </b-collapse>
      </b-card>
    </div>
    

    see https://bootstrap-vue.js.org/docs/components/collapse/#usage:

    <!-- Using value -->
      <b-button v-b-toggle="'collapse-2'" class="m-1">Toggle Collapse</b-button>
    

    EDIT :

    Reviewing my code i noticed that the accordion param in <b-collapse needs to change also, just edit it to :

    :accordion="'productdetails-accordion'+index"
    

    I also edited the code of my first answer