[Vuejs]-Only show one collapse open (Vue 3 / Bootstrap 5)

6๐Ÿ‘

โœ…

A few minor changes to make it work

Your code requires some minor fixes to work correctly. Add the data-bs-parent="#myGroup" attribute to each collapse. And then assign the same id to the parent element of the collapsible elements, i.e., the container.

Note that attribute name has been changed from data-parent in Bootstrap 4 to data-bs-parent in Bootstrap 5. And the parent is the element that contains the collapsible elements and NOT the container of the buttons and links used to toggle.

Additionally, buttons need to have the correct classes applied, e.g., btn-primary and btn-success.

Related SO Question: Collapse other sections when one is expanded

Run the snippet to see how it works:

<div class="row margin-top">
  <div class="col">
    <div class="d-grid gap-2">
      <button type="button" class="btn btn-success" style="height: auto;" data-bs-toggle="collapse" data-bs-target="#collapse-b1" aria-expanded="false" aria-controls="collapse-b1">
        Button 1
      </button>
    </div>
  </div>

  <div class="col">
    <div class="d-grid gap-2">
      <button type="button" class="btn btn-primary" style="height: auto;" data-bs-toggle="collapse" data-bs-target="#collapse-b2" aria-expanded="false" aria-controls="collapse-b2">
        Button 2
      </button>
    </div>
  </div>

</div>

<div id="myGroup">  <!-- Add the parent id here -->

  <div class="collapse" id="collapse-b1"  data-bs-parent="#myGroup">
    <div class="alert alert-success mt-3">
      Text 1
    </div>
  </div>

  <div class="collapse" id="collapse-b2" data-bs-parent="#myGroup">
    <div class="alert alert-primary mt-3">
      Text 2
    </div>
  </div>
  
</div>


<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
๐Ÿ‘คYogi

Leave a comment