Search code examples
vuejs2bootstrap-vue

Toggle elements based on the selected row in the table in vuejs


I am facing an issue where I am trying to use b-collapse in a table and when clicking on the button, it is currently collapsing all the rows in the table.

here is the code for it:

<table class="table b-table border">
        <thead>
          <tr>
            <th class="table-btn"></th>
            <th>name</th>
            <th>last name</th>
            <th>address</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in items" :key="item.id">
            <td class="table-btn">
              <b-button v-b-toggle.collapse-1 variant="primary"
                >Toggle Collapse</b-button
              >
              <b-collapse id="collapse-1" class="mt-2">
                <b-card>
                  <p class="card-text">{{ item.id }}</p>
                </b-card>
              </b-collapse>
            </td>
            <td>{{ item.name }}</td>
            <td>{{ item.lastname }}</td>
            <td>{{ item.address }}</td>
          </tr>
        </tbody>
      </table>

and the script is:

  data() {
    return {
      items: [
        {
          id: 1,
          name: "John",
          lastname: "john@john.com",
          address: "test1",
        },
        {
          id: 2,
          name: "John2",
          lastname: "john2@john.com",
          address: "test2",
        },
      ],
    };
  },

How can I make it to toggle only the on clicking on the selected td/row of the table and display the details.

Here is a sample I am working on: sample

Please advise


Solution

  • It toggless all b-collapse components because you are using v-for and all b-collapse components has same id + all buttons are using this same id in a v-b-toggle directive.

    So the solution is to assign different id for each row...

    <td class="table-btn">
      <b-button v-b-toggle="[`table_collapse_${idx}`]" variant="primary">Toggle Collapse</b-button>
      <b-collapse :id="`table_collapse_${idx}`" class="mt-2">
        <b-card>
          <p class="card-text">{{ item.id }}</p>
        </b-card>
      </b-collapse>
    </td>